←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Notes

Exception Handling in Java: try, catch, finally, throw & throws

Study material and explanations for Unit 3

Exception Handling in Java: try, catch, finally, throw & throws

1. Basic Idea of Exception Handling

  • What is an Exception? An Exception is an abnormal condition or unexpected runtime event (such as dividing a number by zero, accessing an invalid array index, or trying to open a missing file) that disrupts the normal flow of program instructions.
  • What happens if an Exception is NOT handled? The JVM immediately aborts (crashes) the program at that line, prints an ugly technical stack trace, and none of the remaining lines of the program are executed!
  • What is Exception Handling? It is a powerful mechanism to catch runtime errors gracefully, display a user-friendly message, and allow the rest of the program to continue executing normally without crashing.

2. Exception Hierarchy & Checked vs Unchecked Exceptions

In Java, java.lang.Throwable is the root superclass of all errors and exceptions. It splits into two branches:

Figure 3.3: The Exception Hierarchy in Java (java.lang.Throwable)
Throwable (Root Class in java.lang)
1. Exception (Recoverable by Program)
• Checked: IOException, SQLException
• Unchecked (RuntimeException): ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
2. Error (Fatal JVM / Hardware Failures)
Cannot be recovered by code (e.g., OutOfMemoryError, StackOverflowError)

Checked vs Unchecked Exceptions

Feature Checked Exceptions (Compile-Time) Unchecked Exceptions (Runtime)
1. Direct Superclass Subclasses of Exception (excluding RuntimeException). Subclasses of RuntimeException.
2. Checked By Compiler? Yes! Code will not even compile unless you handle them with try-catch or declare them with throws. No! Not checked at compile time; occur at runtime due to logical bugs in code.
3. Common Examples IOException, FileNotFoundException, SQLException, ClassNotFoundException. ArithmeticException (10/0), NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException.

3. The 5 Keywords of Java Exception Handling

Java exception handling is managed using 5 keywords: try, catch, finally, throw, and throws.

Figure 3.4: Execution Flow of try - catch - finally Block
1. try { ... }Monitors risky code that may cause an exception
→ If Exception Occurs →
2. catch (Exception e)Catches & handles the exception object
→ Always Runs →
3. finally { ... }Executes 100% of the time (Closes files/DB)

1. The try Block

  • Encloses the risky statements that might throw an exception at runtime.
  • A try block cannot stand alone—it must be followed by at least one catch block or a finally block.

2. The catch Block

  • Placed immediately after the try block to catch and handle the exception object thrown by the try block.
  • Multiple catch Blocks: A single try block can be followed by multiple catch blocks to handle different types of exceptions specifically (Rule: Always place specific child exceptions like ArithmeticException before the general parent Exception).

3. The finally Block

  • An optional block placed after try-catch that is guaranteed to execute whether an exception occurs or not!
  • Why use finally? Used for cleanup code such as closing open files (file.close()), closing JDBC database connections (conn.close()), or releasing network sockets.

Complete Program Demonstrating try, Multiple catch, and finally

public class TryCatchDemo {
    public static void main(String[] args) {
        try {
            int[] numbers = {10, 20, 30};
            int result = numbers[1] / 0; // Throws ArithmeticException (/ by zero)
            System.out.println("Element: " + numbers[5]); // Would throw ArrayIndexOutOfBoundsException
        }
        catch (ArithmeticException e) {
            System.out.println("Error Caught: Cannot divide a number by zero! (" + e.getMessage() + ")");
        }
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error Caught: Array index is out of range!");
        }
        catch (Exception e) {
            System.out.println("General Exception Caught: " + e);
        }
        finally {
            System.out.println("Finally Block: Always executes to clean up resources!");
        }

        System.out.println("Program continues normally after try-catch-finally.");
    }
}

Output:

Error Caught: Cannot divide a number by zero! (/ by zero)
Finally Block: Always executes to clean up resources!
Program continues normally after try-catch-finally.

4. throw vs throws Keyword in Java

This is the #1 most asked question from Exception Handling in DAVV BCA exams!

A. The throw Keyword (Explicitly Throwing an Exception)

  • Used inside a method body to explicitly create and throw a single exception object (especially for custom validation rules like checking if age < 18 or balance < 0).
  • Syntax: throw new ArithmeticException("Insufficient Balance");

B. The throws Keyword (Declaring Possible Exceptions)

  • Used in the method signature (header) to warn the caller of the method that this method might throw one or more Checked Exceptions (IOException, SQLException) and that the caller must handle them using try-catch.
  • Syntax: void readFile() throws IOException, SQLException { ... }

Comparison Table: throw vs throws

Basis throw Keyword throws Keyword
1. Purpose Used to explicitly throw an exception object from a method or block. Used in a method declaration to indicate/warn what exceptions the method might throw.
2. Where Used? Used inside the method body. Used in the method signature (header).
3. Followed By Followed by a single object instance (throw new Exception();). Followed by one or more Exception Class Names (throws IOException, SQLException).
4. Number of Exceptions Can throw only ONE exception at a time. Can declare MULTIPLE exceptions separated by commas.
5. Main Usage Primarily used for throwing custom / user-defined or unchecked exceptions. Primarily used to propagate Checked Exceptions.

Complete Program Demonstrating Both throw and throws

public class ThrowVsThrowsDemo {

    // 'throws' in method header warns caller about Exception
    static void checkVoterEligibility(int age) throws Exception {
        if (age < 18) {
            // 'throw' inside method body explicitly throws an exception object
            throw new Exception("Age " + age + " is below 18. Not eligible to vote!");
        } else {
            System.out.println("Age " + age + ": Welcome! You are eligible to vote.");
        }
    }

    public static void main(String[] args) {
        try {
            checkVoterEligibility(20); // Valid
            checkVoterEligibility(15); // Triggers 'throw'
        } catch (Exception e) {
            System.out.println("Validation Failed -> " + e.getMessage());
        }
    }
}

Output:

Age 20: Welcome! You are eligible to vote.
Validation Failed -> Age 15 is below 18. Not eligible to vote!

💡 Exam Preparation Tips for DAVV BCA

  • Whenever asked about Exception Handling, always write all 5 keywords (try, catch, finally, throw, throws) and include the throw vs throws comparison table.
  • Remember that throw is followed by an instance (throw new ...), whereas throws is followed by class names (throws IOException).