Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

Exception Handling

Exception handling in Java is a powerful mechanism that allows a program to handle runtime errors gracefully and maintain normal program flow. Instead of abruptly terminating the program when an error occurs, Java provides structured ways to detect, report, and recover from errors. Exception handling improves program reliability, readability, and maintainability, especially in real-world applications.


1. Exception Hierarchy in Java

What is an Exception?

An exception is an unexpected event that occurs during program execution and disrupts the normal flow of the program.

Java Exception Hierarchy

At the top of the hierarchy is the Throwable class.

Throwable
 ├── Error
 └── Exception
      ├── Checked Exceptions
      └── Unchecked Exceptions

1.1 Error

  • Caused by serious system issues
  • Not recoverable
  • Example: OutOfMemoryError, StackOverflowError

1.2 Exception

Exceptions that can be handled by the program.

Checked Exceptions

  • Checked at compile time
  • Must be handled using try-catch or throws
  • Example: IOException, SQLException

Unchecked Exceptions

  • Occur at runtime
  • Not checked by compiler
  • Example: NullPointerException, ArithmeticException

2. try-catch-finally Blocks

Description

The try block contains code that may cause an exception.
The catch block handles the exception.
The finally block executes always, whether an exception occurs or not.


Syntax

try {
    // risky code
} catch (ExceptionType e) {
    // handling code
} finally {
    // cleanup code
}

Example

public class Demo {
    public static void main(String[] args) {
        try {
            int a = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        } finally {
            System.out.println("Execution completed");
        }
    }
}

Explanation

  • Division by zero causes an exception
  • Catch block handles it
  • Finally block executes regardless

3. Multiple catch Blocks

Description

Multiple catch blocks are used to handle different types of exceptions separately.

Rules

  • More specific exceptions should come first
  • Generic exceptions should come last

Syntax

try {
    // code
} catch (ExceptionType1 e) {
} catch (ExceptionType2 e) {
}

Example

public class Test {
    public static void main(String[] args) {
        try {
            int[] arr = new int[5];
            arr[10] = 50;
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic error");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index error");
        } catch (Exception e) {
            System.out.println("General exception");
        }
    }
}

4. throw Keyword

Description

The throw keyword is used to explicitly throw an exception.

Key Points

  • Used inside a method or block
  • Used for custom exception scenarios

Example

public class ThrowExample {
    static void validateAge(int age) {
        if (age < 18) {
            throw new ArithmeticException("Not eligible to vote");
        }
        System.out.println("Eligible to vote");
    }

    public static void main(String[] args) {
        validateAge(16);
    }
}

5. throws Keyword

Description

The throws keyword is used to declare exceptions that a method may pass to the calling method.

Key Points

  • Used in method signature
  • Common with checked exceptions

Example

import java.io.*;

class FileTest {
    void readFile() throws IOException {
        FileReader fr = new FileReader("data.txt");
    }

    public static void main(String[] args) {
        try {
            new FileTest().readFile();
        } catch (IOException e) {
            System.out.println("File not found");
        }
    }
}

throw vs throws

throwthrows
Used to throw exceptionDeclares exception
Inside method bodyIn method signature
Single exceptionMultiple exceptions

6. Custom Exceptions

Description

Custom exceptions are user-defined exceptions created by extending the Exception class. They are used when built-in exceptions are not sufficient.


Steps to Create Custom Exception

  1. Extend Exception class
  2. Create constructor
  3. Throw exception using throw

Example

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

class Bank {
    void withdraw(int amount) throws InvalidBalanceException {
        if (amount > 5000) {
            throw new InvalidBalanceException("Insufficient balance");
        }
        System.out.println("Withdrawal successful");
    }
}

7. Try-With-Resources

Description

Introduced in Java 7, try-with-resources automatically closes resources such as files, database connections, and streams.

Advantages

  • No need for finally block
  • Prevents resource leaks
  • Cleaner code

Syntax

try (resource declaration) {
    // code
}

Example

import java.io.*;

public class ResourceDemo {
public static void main(String[] args) {
try (FileReader fr = new FileReader(“data.txt”)) {
System.out.println(“File opened successfully”);
} catch (IOException e) {
System.out.println(“Error occurred”);
}
}
}

Example of all above content

Example:

java

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

public class ExceptionHandling {
    
    public static void validateAge(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("Age must be 18 or above");
        }
        System.out.println("Age is valid: " + age);
    }
    
    public static void main(String[] args) {
        // Basic try-catch
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide by zero");
        }
        
        // Multiple catch blocks
        try {
            int[] arr = new int[5];
            arr[10] = 50;
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index out of bounds");
        } catch (Exception e) {
            System.out.println("General exception: " + e.getMessage());
        }
        
        // Finally block
        try {
            int x = 5 / 1;
            System.out.println("Result: " + x);
        } catch (Exception e) {
            System.out.println("Exception occurred");
        } finally {
            System.out.println("Finally block always executes");
        }
        
        // Custom exception
        try {
            validateAge(15);
        } catch (InvalidAgeException e) {
            System.out.println("Caught custom exception: " + e.getMessage());
        }
        
        // Try-with-resources (automatic resource management)
        try (Scanner sc = new Scanner(System.in)) {
            System.out.println("Scanner will be closed automatically");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥