Sobes.tech
Junior

What are Exception classes in Java and what types of them exist?

sobes.tech AI

Answer from AI

The Exception classes in Java represent a hierarchy of classes used for handling exceptional situations during program execution. They allow separating error handling logic from the main business logic.

Main types of exceptions in Java:

  • Checked Exceptions:
    • Checked by the compiler (javac).
    • Require explicit handling (using try-catch blocks) or declaration in the method signature (throws).
    • Represent recoverable errors that the program can attempt to fix.
    • Examples: IOException, SQLException, FileNotFoundException, ClassNotFoundException.
    // Example of using a checked exception
    try {
        java.io.FileReader file = new java.io.FileReader("my_file.txt");
        // further file operations
    } catch (java.io.FileNotFoundException e) {
        // handle exception
        e.printStackTrace();
    }
    
  • Unchecked Exceptions:
    • Not checked by the compiler.
    • Inherit from RuntimeException.
    • Not mandatory to handle or declare.
    • Represent runtime errors that often indicate logical errors in the program.
    • Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, IllegalArgumentException.
    // Example of using an unchecked exception
    int[] numbers = {1, 2, 3};
    // Attempt to access an out-of-bounds element
    int number = numbers[5];
    // This will throw ArrayIndexOutOfBoundsException
    
  • Errors:
    • Inherit from Error.
    • Cannot be recovered from under normal circumstances.
    • Represent serious problems related to JVM or runtime environment, such as out of memory or thread errors.
    • Not handled in regular application logic.
    • Examples: OutOfMemoryError, StackOverflowError, VirtualMachineError.
    // Example of an error (usually not handled)
    public class StackOverflowExample {
        public static void recursiveMethod() {
            recursiveMethod(); // infinite recursion
        }
    
        public static void main(String[] args) {
            recursiveMethod(); // This will cause StackOverflowError
        }
    }
    

The exception class hierarchy in Java looks like this:

Throwable
├── Exception
│   ├── Checked Exceptions (e.g., IOException)
│   └── RuntimeException (Unchecked exceptions)
│       └── Unchecked Exceptions (e.g., NullPointerException)
└── Error
    └── JVM Errors (e.g., OutOfMemoryError)

Exception handling is performed using try, catch, finally blocks, and the throw keyword.

What are Exception classes in Java and what types of… - sobes.tech