Java Exception Handling: try-catch-finally, Custom Exceptions & Robust Error Handling for TU BCA

Author: Bhuban Subedi | Subject: Object-Oriented Programming in Java (CACS205) | Semester: Third Semester


In real-world software development, errors are inevitable. A user might type text when a number is expected, a database server might go offline, or an application might attempt to open a file that does not exist.

Without proper error handling, the Java Virtual Machine (JVM) abruptly terminates your program and dumps a cryptic stack trace.

Exception Handling in Java is the robust mechanism that allows programs to intercept runtime errors, handle them gracefully, and continue normal application execution.

In the Tribhuvan University (TU) BCA Third Semester OOP in Java (CACS205) board exams, questions on Exception Hierarchy, throw vs throws, and creating User-Defined (Custom) Exceptions appear repeatedly. Let’s master this topic completely.


1. The Java Exception Hierarchy

Every error and exception in Java inherits from the root class java.lang.Throwable.

                           +------------------------+
                           |  java.lang.Throwable   |
                           +-----------+------------+
                                       |
                   +-------------------+-------------------+
                   |                                       |
                   v                                       v
         +-------------------+                   +-------------------+
         |     Error         |                   |    Exception      |
         | (Fatal JVM issues)|                   | (Recoverable App) |
         +-------------------+                   +---------+---------+
         | OutOfMemoryError  |                             |
         | StackOverflowError|         +-------------------+-------------------+
         +-------------------+         |                                       |
                                       v                                       v
                             +-------------------+                   +-------------------+
                             | Checked Exception |                   | Unchecked (Runtime)|
                             | (Compile-time)    |                   | Exception         |
                             +-------------------+                   +-------------------+
                             | IOException       |                   | NullPointerException
                             | SQLException      |                   | ArithmeticException
                             | ClassNotFoundExc  |                   | ArrayIndexOutBound|
                             +-------------------+                   +-------------------+

2. Checked vs. Unchecked Exceptions: The Key Distinction

In TU viva voce and theory exams, this is a top-tier 5-mark distinction question.

+------------------------------------+------------------------------------+
| Checked Exceptions                 | Unchecked (Runtime) Exceptions     |
+------------------------------------+------------------------------------+
| Directly inherit from `Exception`  | Inherit from `RuntimeException`.   |
| (excluding `RuntimeException`).    |                                    |
+------------------------------------+------------------------------------+
| **Checked at compile-time.** The   | **Not checked at compile-time.**   |
| compiler forces you to handle them | Occur due to programming/logic bugs|
| using `try-catch` or `throws`.     | during runtime.                    |
+------------------------------------+------------------------------------+
| Examples: `IOException`,           | Examples: `ArithmeticException`,   |
| `SQLException`, `FileNotFoundExc`. | `NullPointerException`.            |
+------------------------------------+------------------------------------+

3. The 5 Keywords of Exception Handling

Java provides five keywords to handle exceptions:

  1. try: Surrounds code that might throw an exception.
  2. catch: Handles the specific exception if it occurs.
  3. finally: Block of code that always executes, regardless of whether an exception occurred or was caught (ideal for closing database connections and file streams).
  4. throw: Used explicitly to throw an exception instance inside a method.
  5. throws: Declares in the method signature that this method might throw specific checked exceptions.

4. throw vs. throws: Major Differences

Feature throw throws
Location Used inside the method body. Used in the method signature.
Purpose Actually triggers and throws an exception object. Declares potential exceptions a method may produce.
Syntax Followed by an instance: throw new ArithmeticException(); Followed by class names: throws IOException, SQLException
Count Can throw only one exception instance at a time. Can declare multiple exception classes separated by commas.

5. Creating Custom (User-Defined) Exceptions in Java

In enterprise software, standard Java exceptions like IllegalArgumentException are often too generic. We create custom exceptions by extending java.lang.Exception.

Practical Scenario: Banking System with InsufficientFundsException

Here is a complete, compilable Java program demonstrating custom exceptions, throws, throw, and try-catch-finally.

// Step 1: Define Custom Checked Exception
class InsufficientFundsException extends Exception {
    private double deficitAmount;

    // Constructor accepting error message and deficit amount
    public InsufficientFundsException(String message, double deficitAmount) {
        super(message);
        this.deficitAmount = deficitAmount;
    }

    public double getDeficitAmount() {
        return deficitAmount;
    }
}

// Step 2: Account class that throws the custom exception
class BankAccount {
    private String accountNumber;
    private double balance;

    public BankAccount(String accountNumber, double initialBalance) {
        this.accountNumber = accountNumber;
        this.balance = initialBalance;
    }

    public double getBalance() {
        return balance;
    }

    // Method declaring that it throws InsufficientFundsException
    public void withdraw(double amount) throws InsufficientFundsException {
        System.out.println("\nAttempting withdrawal of Rs. " + amount + " from " + accountNumber);

        if (amount > balance) {
            double deficit = amount - balance;
            // Throw custom exception
            throw new InsufficientFundsException("Transaction Failed: Low Balance!", deficit);
        }

        balance -= amount;
        System.out.println(">> Withdrawal Successful! Remaining Balance: Rs. " + balance);
    }
}

// Step 3: Main driver class demonstrating try-catch-finally
public class CustomExceptionDemo {
    public static void main(String[] args) {
        System.out.println("=== TU BCA JAVA EXCEPTION HANDLING DEMO ===");

        BankAccount myAccount = new BankAccount("TU-BCA-2026-001", 10000.0);
        System.out.println("Initial Balance: Rs. " + myAccount.getBalance());

        // Test Case 1: Valid Withdrawal
        try {
            myAccount.withdraw(4000.0);
        } catch (InsufficientFundsException e) {
            System.err.println("Error: " + e.getMessage());
        }

        // Test Case 2: Exceeding Balance (Triggers Custom Exception)
        try {
            myAccount.withdraw(8000.0); // Only 6000 left
        } catch (InsufficientFundsException e) {
            System.err.println("\n[CAUGHT EXCEPTION] " + e.getMessage());
            System.err.printf("[DETAILS] You are short by: Rs. %.2f\n", e.getDeficitAmount());
        } finally {
            // Finally block always runs
            System.out.println("\n[FINALLY BLOCK] Audit log: Transaction attempt completed.");
            System.out.println("Final Account Balance: Rs. " + myAccount.getBalance());
        }
    }
}

Frequently Asked Questions (FAQ)

Q1: Does the finally block execute if there is a return statement in try or catch?

Yes! The finally block is guaranteed to execute even if a return statement is encountered inside try or catch. The only scenario where finally will not execute is if the JVM process is terminated abruptly via System.exit(0) or a fatal hardware crash.

Q2: What is the “Try-with-Resources” statement introduced in Java 7?

try-with-resources allows automatic resource closing for any object implementing java.lang.AutoCloseable (such as BufferedReader, Connection, Scanner). It eliminates the need for explicit finally cleanup code.

LEAVE A REPLY

Please enter your comment!
Please enter your name here