Object-Oriented Programming in Java

Exception Handling


Module V: Exception Handling. This module explains how Java deals with unexpected conditions during runtime. Exception handling ensures that programs do not crash when errors occur and instead allow controlled recovery.


Exception Handling Fundamentals

An exception is an event that disrupts the normal flow of the program. Java uses a robust, object-oriented model for error handling.

  • Exception – indicates runtime errors that can be handled
  • Error – serious issues not expected to be handled (e.g. OutOfMemoryError)
  • All exceptions derive from the class Throwable

The main advantage of Java's exception system is **separation of error-handling code from normal logic**.

Diagram: exception-hierarchy.png


Types of Exceptions

  • Checked exceptions – must be caught or declared (IOException, SQLException)
  • Unchecked exceptions – inherit from RuntimeException (ArithmeticException, NullPointerException)
  • Errors – not meant to be handled (StackOverflowError)
Unchecked Exception Example
int x = 10 / 0;   // ArithmeticException
Checked Exception Example
FileReader fr = new FileReader("abc.txt");   // must be handled

Using try, catch, and finally

A try block contains statements that may throw an exception.catch blocks handle the specific exception types. The finally block executes whether or not an exception occurs.

try {
  int a = 5 / 0;
} catch (ArithmeticException e) {
  System.out.println("Cannot divide by zero");
} finally {
  System.out.println("Cleanup operations");
}
  • Use multiple catch blocks for multiple exception types
  • finally is often used to close files, connections, or release resources

throw and throws

throw explicitly throws an exception.throws declares that a method may throw an exception.

void checkAge(int age) {
  if(age < 18)
    throw new IllegalArgumentException("Too young");
}

void readFile() throws IOException {
  FileReader f = new FileReader("data.txt");
}

Java’s Built-in Exceptions

Commonly asked in exams:

  • ArithmeticException
  • ArrayIndexOutOfBoundsException
  • NullPointerException
  • NumberFormatException
  • IOException

Creating Custom Exceptions

User-defined exceptions extend the Exception class.

class InvalidMarksException extends Exception {
  InvalidMarksException(String msg) {
    super(msg);
  }
}

void check(int m) throws InvalidMarksException {
  if(m < 0 || m > 100)
    throw new InvalidMarksException("Invalid marks");
}

Summary

Exception handling improves program reliability by allowing controlled error management. Using try-catch-finally, throwing exceptions, and understanding the exception class hierarchy are essential skills for robust Java development.

Diagrams to insert: try-catch-flowchart.png, exception-types-table.png