Skip to content

Lesson 1: Understanding Exceptions

Overview:

Lesson 1 Understanding Exceptions focuses on understanding exceptions in Java, which are events that disrupt the normal flow of a program. Handling exceptions is essential for writing robust and error-tolerant applications. This lesson covers the basics of handling errors in Java and introduces different types of exceptions.

Key Concepts:

  1. Exception Handling:
    • Definition: The process of dealing with unexpected events that occur during the execution of a program.
    • Purpose: Ensures that a program can gracefully recover from errors without terminating abruptly.
  2. Types of Exceptions:
    • Checked Exceptions:
      • Definition: Exceptions that are checked at compile-time.
      • Example: IOException, ClassNotFoundException.
      • Handling: Required to be caught or declared by the method using try-catch or throws clause.
    • Unchecked Exceptions (Runtime Exceptions):
      • Definition: Exceptions that are not checked at compile-time.
      • Example: NullPointerException, ArrayIndexOutOfBoundsException.
      • Handling: Optional; can be caught using try-catch or left to be handled at runtime.
    • Error:
      • Definition: Serious problems that a reasonable application should not try to catch.
      • Example: OutOfMemoryError, StackOverflowError.
      • Handling: Generally not caught or handled; signifies severe issues beyond the application’s control.

Example:

Let’s create a program that demonstrates the basics of exception handling in Java. We’ll intentionally provoke a divide-by-zero error and handle it using a try-catch block.

import java.util.Scanner;

public class ExceptionHandlingExample {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        try {
            System.out.print("Enter numerator: ");
            int numerator = scanner.nextInt();

            System.out.print("Enter denominator: ");
            int denominator = scanner.nextInt();

            int result = divide(numerator, denominator);
            System.out.println("Result of division: " + result);
        } catch (ArithmeticException e) {
            System.err.println("Error: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("An unexpected error occurred: " + e.getMessage());
        } finally {
            scanner.close();
        }
    }

    private static int divide(int numerator, int denominator) {
        if (denominator == 0) {
            throw new ArithmeticException("Cannot divide by zero.");
        }
        return numerator / denominator;
    }
}

In this example, the divide method intentionally throws an ArithmeticException if the denominator is zero. The main method uses a try-catch block to handle this exception, providing a message in case of an error. The finally block ensures that the Scanner is closed, even if an exception occurs.