Java Exceptions

Exceptions in Java are events that occur during the execution of a program that disrupt the normal flow of instructions. Java provides a robust and object-oriented way to handle exceptions, allowing you to write code that can deal with unexpected situations gracefully.

1. Types of Exceptions

  • Checked Exceptions: Exceptions that are checked at compile-time. They must be either caught or declared in the method's throws clause.
  • Unchecked Exceptions: Exceptions that are not checked at compile-time. They include RuntimeException and its subclasses.
  • Errors: Serious problems that applications should not try to catch (e.g., OutOfMemoryError).

2. The try-catch-finally Block

Used to catch and handle exceptions.

Syntax:

try {
    // Code that may throw an exception
} catch (ExceptionType e) {
    // Handle exception
} finally {
    // Optional block executed regardless of exception
}

3. Throwing Exceptions

You can throw an exception explicitly using the throw keyword.

if (age < 0) {
    throw new IllegalArgumentException("Age cannot be negative.");
}

4. Creating Custom Exceptions

You can create your own exception classes by extending Exception or RuntimeException.

public class InvalidInputException extends Exception {
    public InvalidInputException(String message) {
        super(message);
    }
}

5. Key Takeaways

  • Exceptions help in handling runtime errors gracefully.
  • Use try-catch-finally blocks to catch and handle exceptions.
  • Checked exceptions must be declared or handled.
  • Unchecked exceptions do not need to be declared or caught.
  • Creating custom exceptions can provide more meaningful error handling.