Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Core Java - Exception Handling

13. Exception Handling

Exception handling is a crucial aspect of Java programming that allows you to gracefully handle errors and unexpected situations that may occur during the execution of your program. In this Core Java tutorial, we'll explore exception handling in detail, providing explanations and examples.

What is an Exception?

An exception is an abnormal event or runtime error that occurs during the execution of a Java program. These exceptions can be caused by a variety of reasons, such as incorrect input, file not found, division by zero, and more.

Exception Hierarchy in Java:

Java's exception hierarchy is organized into two main categories:

  • Checked Exceptions: These exceptions are checked at compile-time. You are required to either catch them using a 'try-catch' block or declare that your method throws them using the 'throws' keyword.

  • Unchecked Exceptions (Runtime Exceptions): These exceptions are not checked at compile-time and can occur at runtime. They typically represent programming errors, and it's not mandatory to catch or declare them.

Handling Exceptions in Java

  • 'try-catch' Blocks :

A 'try-catch' block is used to handle exceptions. The code that might throw an exception is placed inside the 'try' block, and the code to handle the exception is placed inside the 'catch' block.

try {
    // Code that may cause an exception
} catch (ExceptionType e) {
    // Code to handle the exception
}
 
Example:
try {
    int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Error: " + e.getMessage());
}
 

In this example, an 'ArithmeticException'  is caught and handled.

  • 'finally' Block:

The 'finally' block, if provided, is executed regardless of whether an exception is thrown or not. It's typically used to release resources like file handles or network connections.

try {
    // Code that may cause an exception
} catch (ExceptionType e) {
    // Code to handle the exception
} finally {
    // Code that always runs, whether an exception occurred or not
}
 
Example:
FileInputStream file = null;
try {
    file = new FileInputStream("myfile.txt");
    // Read and process the file
} catch (FileNotFoundException e) {
    System.out.println("File not found: " + e.getMessage());
} finally {
    try {
        if (file != null) {
            file.close();
        }
    } catch (IOException e) {
        System.out.println("Error closing file: " + e.getMessage());
    }
}
 

In this example, the 'finally' block ensures that the file is closed, even if an exception occurs during file processing or if the file is not found.

Propagating Exceptions with 'throws':

When a method can potentially throw a checked exception, you can either handle it using a 'try-catch' block or declare it in the method signature using the 'throws' keyword.

public void myMethod() throws ExceptionType {
    // Code that may throw an exception
}
 

Creating Custom Exceptions:

You can create custom exceptions by extending the 'Exception'class or one of its subclasses. This allows you to define your own exception types tailored to your application's specific needs.

class MyCustomException extends Exception {
    public MyCustomException(String message) {
        super(message);
    }
}
 
Example:
public void myMethod(int value) throws MyCustomException {
    if (value < 0) {
        throw new MyCustomException("Value cannot be negative");
    }
    // Rest of the method
}
 

In this example, 'MyCustomException' is a custom exception that is thrown when the 'value'  is negative.

Using 'try-with-resources' (Java 7+):

Java introduced the 'try-with-resources' statement to automatically close resources like streams, files, and database connections when they are no longer needed. This simplifies resource management and exception handling.

try (ResourceType resource = new ResourceType()) {
    // Code that uses the resource
} catch (ExceptionType e) {
    // Code to handle exceptions
}
 
Example:
try (BufferedReader reader = new BufferedReader(new FileReader("myfile.txt"))) {
    String line = reader.readLine();
    while (line != null) {
        System.out.println(line);
        line = reader.readLine();
    }
} catch (IOException e) {
    System.out.println("Error reading file: " + e.getMessage());
}
 

In this example, the 'BufferedReader' is automatically closed when the 'try' block exits, regardless of whether an exception occurred.

Conclusion:

Exception handling is a vital part of writing robust Java programs. It allows you to handle errors gracefully, prevent program crashes, and provide informative error messages to users. Understanding how to use'try-catch' blocks, 'finally' blocks, and custom exceptions is essential for developing reliable Java applications. Additionally, the 'try-with-resources' statement simplifies resource management and improves code readability.