codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
☕

Java Programming

40 / 65 topics
40Java Exceptions41Java Multiple Exceptions42Java try-with-resources
Tutorials/Java Programming/Java Exceptions
☕Java Programming

Java Exceptions

Updated 2026-05-12
30 min read

Java Exceptions

In the world of programming, errors are inevitable. They can occur due to various reasons such as invalid user input, unexpected file operations, or network issues. Java provides a robust exception handling mechanism to manage these errors gracefully and ensure that your program continues to run smoothly even when faced with unexpected situations.

Exception handling in Java is crucial for building reliable applications. It allows developers to separate error-handling code from the main logic of their programs, making the code cleaner and more maintainable. In this tutorial, we'll explore how to handle exceptions using try, catch, finally, throw, and understand the distinction between checked and unchecked exceptions.

Introduction

An exception in Java is an event that disrupts the normal flow of a program's execution. When an error occurs, an exception object is created and thrown. If not handled properly, this can cause your program to crash. However, with proper exception handling, you can catch these exceptions and take appropriate actions.

Exception handling in Java involves several key components:

  • try: A block of code where you expect an exception might occur.
  • catch: A block of code that handles the exception if it occurs.
  • finally: A block of code that executes regardless of whether an exception was thrown or not, typically used for cleanup activities.
  • throw: Used to explicitly throw an exception.
  • throws: Used in method signatures to declare that a method might throw certain exceptions.

Handling Exceptions with try and catch

The try and catch blocks are the core components of Java's exception handling mechanism. The try block contains code that might throw an exception, while the catch block handles the exception if it occurs.

Example 1: Basic Try-Catch Block

Java
1// Example1.java
2public class Example1 {
3 public static void main(String[] args) {
4 try {
5 int result = 10 / 0; // This will throw an ArithmeticException
6 System.out.println("Result: " + result);
7 }; catch (ArithmeticException e) {
8 System.out.println("Error: Division by zero is not allowed.");
9 }
10 }
11}
Output

Here, the try block contains two statements that might throw exceptions. The first statement throws an ArithmeticException, which is caught by the first catch block. If no exception occurs in the first statement but the second statement throws a NullPointerException, it is caught by the second catch block.

Finally Block

The finally block is optional and always executes after the try and catch blocks, regardless of whether an exception was thrown or not. It's commonly used for cleanup activities such as closing files, releasing network connections, or freeing up resources.

Example 3: Using Finally Block

Java
1// Example3.java
2public class Example3 {
3 public static void main(String[] args) {
4 try {
5 int result = 10 / 0; // This will throw an ArithmeticException
6 System.out.println("Result: " + result);
7 } catch (ArithmeticException e) {
8 System.out.println("Error: Division by zero is not allowed.");
9 } finally {
10 System.out.println("Execution completed.");
11 }
12 }
13}
Output
Error: Division by zero is not allowed.
Execution completed.

In this example, the finally block executes regardless of whether an exception was thrown or not.

Throwing Exceptions

You can explicitly throw exceptions using the throw keyword. This is useful when you want to signal that something exceptional has occurred in your code.

Example 4: Throwing Custom Exception

Java
1// Example4.java
2public class Example4 {
3 public static void main(String[] args) {
4 try {
5 checkAge(15);
6 } catch (Exception e) {
7 System.out.println(e.getMessage());
8 }
9 }
10
11 public static void checkAge(int age) throws Exception {
12 if (age < 18) {
13 throw new Exception("Access denied - You must be at least 18 years old.");
14 }
15 System.out.println("Access granted - You are old enough!");
16 }
17}
Output

In this example, FileNotFoundException is a checked exception. If you try to compile and run this code without handling it, the compiler will throw an error.

Practical Example

Let's create a practical example that demonstrates how to handle multiple exceptions in a real-world scenario. We'll write a program that reads data from a file and handles various potential errors.

Example 6: File Reading with Exception Handling

Java
1// FileReadingExample.java
2import java.io.File;
3import java.io.FileReader;
4import java.io.FileNotFoundException;
5import java.io.IOException;
6
7public class FileReadingExample {
8 public static void main(String[] args) {
9 try {
10 File file = new File("data.txt");
11 FileReader fr = new FileReader(file);
12 int i;
13 while ((i = fr.read()) != -1) {
14 System.out.print((char) i);
15 }
16 fr.close();
17 } catch (FileNotFoundException e) {
18 System.out.println("Error: File not found.");
19 } catch (IOException e) {
20 System.out.println("Error: An I/O error occurred.");
21 } finally {
22 System.out.println("
23Execution completed.");
24 }
25 }
26}
Output
Error: File not found.
Execution completed.

In this example, the program attempts to read data from a file named data.txt. If the file does not exist, it catches a FileNotFoundException. If an I/O error occurs during reading, it catches an IOException. The finally block ensures that the message "Execution completed." is printed regardless of whether an exception was thrown.

Summary

  • try: Contains code that might throw an exception.
  • catch: Handles exceptions if they occur.
  • finally: Executes after try and catch blocks, used for cleanup activities.
  • throw: Explicitly throws an exception.
  • throws: Declares that a method might throw certain exceptions.
TypeDescription
CheckedMust be declared or caught. Represents recoverable errors.
UncheckedDo not need to be declared or caught. Represents programming errors.

What's Next?

In the next tutorial, we'll explore how to handle multiple exceptions in a single catch block and use custom exception classes to create more robust error handling mechanisms. Stay tuned!

Terminal
$ javac FileReadingExample.java
$ java FileReadingExample

PreviousJava DateNext Java Multiple Exceptions

Recommended Gear

Java DateJava Multiple Exceptions