CACS204 Object Oriented Programming in Java

Object Oriented Programming in JavaUnit 68 min read

Exception Handling in Java: Errors, Try-Catch, Custom Exceptions & Best Practices

Unit 6 of Object Oriented Programming in Java covers how to handle runtime errors gracefully using Java’s exception hierarchy, try-catch-finally blocks, and custom exceptions—with real-world examples from Nepali apps like eSewa and Kathmandu traffic systems, plus code traces and GUI integration.

Key Concepts & Definitions

1. What is an Exception?

An exception is an unexpected event that disrupts normal program execution. Java divides exceptions into two categories:

classDiagram
    class Exception {
        +String getMessage()
        +void printStackTrace()
    }
    class RuntimeException {
        <<unchecked>>
        +ArithmeticException
        +NullPointerException
        +ArrayIndexOutOfBoundsException
    }
    class IOException {
        <<checked>>
        +FileNotFoundException
        +EOFException
    }
    Exception <|-- RuntimeException
    Exception <|-- IOException

Key Differences:

Feature Checked Exception Unchecked Exception (RuntimeException)
Inheritance Extends Exception Extends RuntimeException
Handling Must be handled Optional to handle
Examples IOException, SQLException ArithmeticException, NullPointerException
When thrown External factors (e.g., file not found) Programming errors (e.g., division by zero)

2. Exception Handling Mechanism

Java uses try, catch, finally, and throw/throws to handle exceptions.

Syntax Breakdown

try {
    // Risky code (may throw an exception)
} catch (ExceptionType1 e1) {
    // Handle ExceptionType1
} catch (ExceptionType2 e2) {
    // Handle ExceptionType2
} finally {
    // Always executes (e.g., closing resources)
}

Example: Dividing Two Numbers

public class ExceptionDemo {
    public static void main(String[] args) {
        int a = 10, b = 0;
        try {
            int result = a / b; // Throws ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero!");
            e.printStackTrace(); // Prints stack trace
        } finally {
            System.out.println("Execution complete.");
        }
    }
}

Trace Table:

Step Code Executed Exception Thrown? Output
1 int result = a / b; Yes (ArithmeticException) None (jumps to catch)
2 catch block No "Cannot divide by zero!"
3 finally block No "Execution complete."

3. Custom Exceptions

Create domain-specific exceptions by extending Exception or RuntimeException.

Example: InvalidAgeException for eSewa

class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);
    }
}

public class eSewaAgeCheck {
    public static void validateAge(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("Age must be 18+ to use eSewa.");
        }
        System.out.println("Access granted.");
    }

    public static void main(String[] args) {
        try {
            validateAge(15); // Throws InvalidAgeException
        } catch (InvalidAgeException e) {
            System.err.println(e.getMessage());
        }
    }
}

Output:

Age must be 18+ to use eSewa.

4. Real-World Applications in Nepal

a) eSewa: Transaction Validation

  • Idea Used: Custom exceptions for invalid transactions.
  • How?
    • If a user enters an invalid PIN, eSewa throws a SecurityException.
    • If the account balance is insufficient, it throws an InsufficientFundsException.
    • Example:
      if (balance < amount) {
          throw new InsufficientFundsException("Insufficient balance.");
      }
      

b) Kathmandu Traffic System: Route Planning

  • Idea Used: IOException for GPS data errors.
  • How?
    • If the GPS fails to fetch real-time traffic data, the system catches IOException and suggests an alternative route.
    • Example:
      try {
          String trafficData = fetchGPSData(); // May throw IOException
      } catch (IOException e) {
          System.out.println("Using cached route data.");
      }
      

c) Ncell: SIM Registration

  • Idea Used: IllegalArgumentException for invalid phone numbers.
  • How?
    • If a user enters a 9-digit number (instead of 10), Ncell throws:
      if (phoneNumber.length() != 10) {
          throw new IllegalArgumentException("Phone number must be 10 digits.");
      }
      

5. Exception Handling in GUI Programs

Example: Even/Odd Checker (Past Exam Question)

import javax.swing.*;
import java.awt.event.*;

public class EvenOddChecker extends JFrame {
    private JTextField numField;
    private JLabel resultLabel;

    public EvenOddChecker() {
        numField = new JTextField(10);
        JButton checkButton = new JButton("Check");
        resultLabel = new JLabel("");

        checkButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    int num = Integer.parseInt(numField.getText());
                    if (num % 2 == 0) {
                        resultLabel.setText(num + " is even.");
                    } else {
                        resultLabel.setText(num + " is odd.");
                    }
                } catch (NumberFormatException ex) {
                    resultLabel.setText("Enter a valid number!");
                }
            }
        });

        add(numField); add(checkButton); add(resultLabel);
        setLayout(new FlowLayout());
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new EvenOddChecker().setVisible(true);
    }
}

GUI State After Input "abc":



6. Best Practices

  1. Catch Specific Exceptions First: Always catch more specific exceptions before general ones.
    catch (FileNotFoundException e) { ... } // Before IOException
    catch (IOException e) { ... }
    
  2. Use finally for Cleanup: Close files, database connections, or network sockets.
    FileInputStream fis = null;
    try {
        fis = new FileInputStream("data.txt");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (fis != null) fis.close(); // Ensures resource is released
    }
    
  3. Avoid Empty Catch Blocks: Log exceptions or rethrow them.
    // Bad:
    catch (Exception e) {} // Silently ignores errors
    
    // Good:
    catch (Exception e) {
        logger.log(e);
        throw e;
    }
    
  4. Document Thrown Exceptions: Use @throws in Javadoc.
    /**
     * @throws IOException if file cannot be read
     */
    public void readFile() throws IOException { ... }
    

7. Common Pitfalls

Mistake Fix
Catching Exception too broadly Catch specific exceptions
Swallowing exceptions silently Log or handle meaningfully
Not closing resources in finally Use try-with-resources (Java 7+)
Throwing exceptions for flow control Use flags or return values instead

Example of try-with-resources (Java 7+):

try (FileInputStream fis = new FileInputStream("data.txt")) {
    // Automatically closes fis when block exits
} catch (IOException e) {
    e.printStackTrace();
}

Exam Tip

  1. For Theory Questions:

    • Differentiate checked vs. unchecked exceptions clearly (use the table above).
    • Explain the purpose of finally (e.g., releasing resources).
    • Define custom exceptions and when to use them (e.g., domain validation).
  2. For Programming Questions:

    • Always include try-catch in GUI programs (e.g., input validation).
    • Trace exceptions step-by-step (show the output for invalid inputs).
    • Use throws in method signatures if the exception isn’t handled locally.
  3. Past Exam Patterns:

    • Combine exception handling with file I/O or GUI validation.
    • Example question: "Write a program to read a file and handle FileNotFoundException."

Visual Summary:

Based on the TU BCA syllabus for Object Oriented Programming in Java (CACS204), unit 6.

Discussion

Loading…