fbpx

Exception types

In Java, exceptions are categorized into two main types: checked exceptions and unchecked exceptions. The distinction between these types influences how they are handled in the code.

1. Checked Exceptions:

Checked exceptions are exceptions that the compiler forces you to either catch or declare in the method signature using the throws keyword. They extend the Exception class or one of its subclasses (excluding RuntimeException and its subclasses).

Example of Checked Exception:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class CheckedExceptionExample {
    public static void main(String[] args) {
        try {
            FileInputStream file = new FileInputStream("example.txt");
            // Code that uses the FileInputStream
            file.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("IOException: " + e.getMessage());
        }
    }
}

In this example, FileNotFoundException and IOException are checked exceptions, and the code must handle them using try-catch blocks.

2. Unchecked Exceptions (Runtime Exceptions):

Unchecked exceptions, also known as runtime exceptions, do not need to be explicitly caught or declared. They extend the RuntimeException class or one of its subclasses.

Example of Unchecked Exception:

public class UncheckedExceptionExample {
    public static void main(String[] args) {
        int[] array = {1, 2, 3};
        try {
            // Accessing an element outside the array bounds
            int value = array[5];
            System.out.println("Value: " + value);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index out of bounds: " + e.getMessage());
        }
    }
}

In this example, ArrayIndexOutOfBoundsException is an unchecked exception. The code does not need to declare it in a throws clause, and catching it is optional.

3. Common Exception Classes in Java:

Some common checked exception classes:

  • IOException (and its subclasses): Signals issues with I/O operations.
  • ClassNotFoundException: Indicates that a class could not be found during runtime reflection.

Some common unchecked exception classes:

  • NullPointerException: Thrown when attempting to access an object or invoke a method on a null reference.
  • ArrayIndexOutOfBoundsException: Raised when trying to access an array element with an invalid index.
  • ArithmeticException: Occurs when an arithmetic operation, such as division by zero, is performed.

4. Custom Exceptions:

Developers can create their own exception classes by extending either Exception (for checked exceptions) or RuntimeException (for unchecked exceptions). Custom exceptions allow for more specific error handling and meaningful messages.

Example of Custom Exception:

class CustomException extends RuntimeException {
    CustomException(String message) {
        super(message);
    }
}

public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            throw new CustomException("This is a custom exception");
        } catch (CustomException e) {
            System.out.println("Caught custom exception: " + e.getMessage());
        }
    }
}

Conclusion:

Understanding the types of exceptions in Java is essential for writing robust and error-tolerant code. Checked exceptions provide a way to handle anticipated issues during compilation, while unchecked exceptions allow for more flexibility in error management. Whether handling built-in exceptions or creating custom ones, proper exception handling contributes to the reliability and maintainability of Java applications.