DEV Community

Sudhakar V
Sudhakar V

Posted on

Exceptions in Java

Exceptions in Java are events that disrupt the normal flow of a program's execution. They are used to handle errors and other exceptional events that may occur during runtime.

Types of Exceptions

  1. Checked Exceptions (compile-time exceptions)

    • Must be declared or handled (using try-catch or throws)
    • Examples: IOException, SQLException, ClassNotFoundException
  2. Unchecked Exceptions (runtime exceptions)

    • Not checked at compile time
    • Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException
  3. Errors

    • Serious problems that applications should not try to catch
    • Examples: OutOfMemoryError, StackOverflowError

Exception Handling Keywords

  • try: Block of code to monitor for exceptions
  • catch: Block that handles the exception
  • finally: Block that always executes (for cleanup)
  • throw: Used to explicitly throw an exception
  • throws: Declares exceptions that might be thrown by a method

Example

try {
    // Code that might throw an exception
    int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
} catch (Exception e) {
    System.out.println("General exception caught");
} finally {
    System.out.println("This will always execute");
}
Enter fullscreen mode Exit fullscreen mode

Custom Exceptions

You can create your own exception classes by extending Exception (checked) or RuntimeException (unchecked):

class MyCustomException extends Exception {
    public MyCustomException(String message) {
        super(message);
    }
}
Enter fullscreen mode Exit fullscreen mode

Best Practices

  1. Catch specific exceptions rather than general Exception
  2. Don't ignore caught exceptions (empty catch blocks)
  3. Use finally blocks for resource cleanup
  4. Document exceptions with @throws in JavaDoc
  5. Consider whether to handle, propagate, or convert exceptions

Would you like more details on any specific aspect of Java exceptions?

Top comments (0)