Skip to content

Week 11: Java – Exception Handling


Q1. Division with Exception Handling

Objective: Safely handle division by zero using try-catch.

import java.util.Scanner;

class q1 {

    public Integer divide(int a, int b) {
        try {
            return a / b; // may throw ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide by zero.");
            return null; // return null instead of crashing
        }
    }

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

        System.out.print("Numerator: ");
        int numerator = sc.nextInt();

        System.out.print("Denominator: ");
        int denominator = sc.nextInt();

        Integer result = calc.divide(numerator, denominator);

        if (result != null) {
            System.out.println("Result: " + result);
        } else {
            System.out.println("Program continues safely.");
        }

        sc.close();
    }
}

Key Points:

  • try-catch handles runtime exceptions (ArithmeticException).
  • Program does not crash on division by zero.
  • Returning null allows the program to continue safely.

Q2. File Reading with Checked Exceptions

Objective: Handle both checked (IOException) and unchecked (IllegalArgumentException) exceptions.

import java.io.IOException;

class FileReaderUtility {

    public static void readFile(String fileName) throws IOException {

        if (fileName.isEmpty()) {
            throw new IllegalArgumentException("Filename cannot be empty.");
        }

        if (fileName.equals("missing.txt")) {
            throw new IOException("File not found.");
        }

        System.out.println("Reading file: " + fileName);
    }
}

public class q2 {
    public static void main(String[] args) {

        String[] files = {"data.txt", "", "missing.txt"};

        for (String file : files) {
            try {
                FileReaderUtility.readFile(file);
            }
            catch (IllegalArgumentException e) {
                System.out.println("Error: " + e.getMessage());
            }
            catch (IOException e) {
                System.out.println("Error: " + e.getMessage());
            }
            finally {
                // Optional cleanup can be placed here
            }
        }
    }
}

Key Points:

  • IOException is a checked exception – must be declared or caught.
  • IllegalArgumentException is unchecked – can occur at runtime.
  • finally block executes regardless of exception, useful for cleanup.
  • Using multiple catch blocks allows handling different exception types separately.

Week 11 Concepts Summary

  1. Try-Catch

  2. Wrap risky code in try.

  3. Handle exceptions in catch.
  4. Checked vs Unchecked Exceptions

  5. Checked: must be handled (IOException, FileNotFoundException).

  6. Unchecked: optional handling (ArithmeticException, IllegalArgumentException).
  7. Finally Block

  8. Executes always, even if exception occurs.

  9. Often used for closing resources (files, DB connections).
  10. Exception Propagation

  11. Use throws in method signature to propagate exceptions.


Comments