Even correct programs meet unusual conditions while running: a file is missing, a number is divided by zero, or input is not a number. Exception handling lets a program deal with them gracefully.

What is an Exception?

An exception is an event that occurs during the execution of a program and disrupts its normal flow. When an error occurs in a method, Java creates an exception object that describes it and throws it. If the program does not handle it, the JVM's default handler prints an error message with a stack trace and ends the program. Exception handling lets the program catch the exception, take corrective action, and continue, which makes programs robust and keeps error-handling code apart from normal code.

Definition: Exception. An object representing an abnormal condition that arises during the execution of a program and disrupts its normal flow, which can be caught and handled.

Exception Hierarchy

All exceptions are subclasses of Throwable, which has two branches. Error represents serious problems in the JVM, such as OutOfMemoryError and StackOverflowError, which programs should not try to handle. Exception represents conditions that programs can handle. A subclass of Exception, RuntimeException, covers programming errors.

Checked and Unchecked Exceptions

Checked exceptions are checked by the compiler: a method that may throw one must either catch it or declare it with throws, otherwise the program does not compile. Examples are IOException, FileNotFoundException and SQLException. Unchecked exceptions are RuntimeException and its subclasses, and are not checked by the compiler. Examples are ArithmeticException (division by zero), ArrayIndexOutOfBoundsException, NullPointerException, NumberFormatException (as from Integer.parseInt("abc")) and ClassCastException.

The Keywords

Java has five keywords for exceptions: try encloses code that may throw an exception; catch handles an exception of a given type; finally encloses code that always runs; throw throws an exception explicitly; and throws declares that a method may throw an exception.

try and catch

The basic form is: try { risky code } catch (ExceptionType e) { handling code }. When an exception occurs in the try block, the rest of the block is skipped and control passes to the matching catch block. After the catch block, execution continues after the try-catch. The exception object gives details through e.getMessage() and e.printStackTrace().

Table 4.3: Common exceptions

Exception Cause Type
ArithmeticException Integer division by zero Unchecked
ArrayIndexOutOfBoundsException Bad array index Unchecked
NullPointerException Using a null reference Unchecked
NumberFormatException Bad number string Unchecked
IOException Input-output failure Checked

Example 4.3: Divide by zero

Problem: Write a program that divides 100 by a number, handles division by zero, and continues.

Solution:

  1. Put the division in a try block.
  2. Catch ArithmeticException and print a message with e.getMessage().
  3. Print a line after the try-catch to show that the program continues.

Result: The exception is caught, a message is printed, and the program ends normally.

public class DivideByZero {
    public static void main(String[] args) {
        int[] divisors = {5, 0};
        for (int d : divisors) {
            try {
                int result = 100 / d;
                System.out.println("100 / " + d + " = " + result);
            } catch (ArithmeticException e) {
                System.out.println("Error: " + e.getMessage());
            }
        }
        System.out.println("Program continues normally.");
    }
}

Output

100 / 5 = 20
Error: / by zero
Program continues normally.

Common mistakes

  • Trying to catch Error types such as OutOfMemoryError in normal programs.
  • Ignoring a checked exception, which causes a compile error.
  • Writing an empty catch block, which hides the problem.

Key takeaways

  • An exception disrupts the normal flow and is thrown as an object.
  • Throwable splits into Error and Exception.
  • Checked exceptions must be caught or declared; unchecked ones need not be.
  • try encloses risky code; catch handles the exception.

Practice questions

  1. What is an exception?
  2. Distinguish checked and unchecked exceptions.
  3. Name the five exception-handling keywords.

Answers to the practice questions

  1. An abnormal event during execution that disrupts the normal flow and is represented by an object.
  2. Checked exceptions are checked by the compiler and must be handled or declared; unchecked ones are subclasses of RuntimeException and need not be.
  3. try, catch, finally, throw and throws.

Sources

  • Official BCA syllabus Object Oriented Programming using Java, course code 25BCA402SEC01, Unit IV