Thursday, November 27, 2025

thumbnail

Exception Handling in Java

 Exception Handling in Java


Exception handling in Java is a mechanism that allows developers to detect, handle, and recover from runtime errors without crashing the entire application. It improves program stability, readability, and maintainability.


1. What Is an Exception?


An exception is an event that disrupts the normal flow of a Java program.

Exceptions occur during runtime and can be caused by:


Dividing a number by zero


Accessing an invalid array index


Opening a file that does not exist


Invalid user input


Network or database errors


When an exception occurs, Java creates an exception object and hands it to the runtime system.


2. Exception Hierarchy in Java


Java exceptions are part of the java.lang package.


Throwable

 ├── Error (not meant to be handled – e.g., OutOfMemoryError)

 └── Exception

        ├── Checked Exceptions (must be handled)

        └── Unchecked Exceptions (RuntimeExceptions)


✔ Errors


Serious problems the application shouldn’t handle


Example: OutOfMemoryError, StackOverflowError


✔ Checked Exceptions


Must be handled using try-catch or throws


Example: IOException, SQLException


✔ Unchecked Exceptions (RuntimeExceptions)


Usually due to programming mistakes


Example: NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException


3. The Try-Catch Block


Java handles exceptions using the try-catch structure.


Basic Syntax

try {

    // code that may cause an exception

} catch (ExceptionType e) {

    // code to handle the exception

}


Example

try {

    int num = 10 / 0;

} catch (ArithmeticException e) {

    System.out.println("Cannot divide by zero!");

}


4. Multiple Catch Blocks


Java lets you catch different exception types separately.


try {

    int[] arr = new int[3];

    System.out.println(arr[5]);

} catch (ArrayIndexOutOfBoundsException e) {

    System.out.println("Invalid array index!");

} catch (Exception e) {

    System.out.println("General exception occurred.");

}


5. The Finally Block


The finally block runs whether an exception occurs or not.

Useful for cleanup tasks like closing files, connections, or releasing resources.


try {

    FileReader fr = new FileReader("file.txt");

} catch (FileNotFoundException e) {

    System.out.println("File not found!");

} finally {

    System.out.println("This always executes.");

}


6. The Throws Keyword


If a method might cause a checked exception, you can declare it using the throws keyword.


public void readFile() throws IOException {

    FileReader reader = new FileReader("data.txt");

}



This passes the responsibility of handling the exception to the method that calls it.


7. Throwing Exceptions Manually (throw)


You can throw an exception yourself using throw.


public void validateAge(int age) {

    if (age < 18) {

        throw new IllegalArgumentException("Age must be 18 or above.");

    }

}


8. Custom Exceptions


You can create your own exception classes by extending Exception or RuntimeException.


class InvalidScoreException extends Exception {

    public InvalidScoreException(String message) {

        super(message);

    }

}


9. Best Practices for Exception Handling

✔ Catch specific exceptions


Avoid catching generic Exception unless necessary.


✔ Don’t swallow exceptions


Always log or handle them properly.


✔ Use finally or try-with-resources


Prevents resource leaks.


✔ Throw exceptions with meaningful messages


Helps debugging.


✔ Avoid using exceptions for flow control


Use them only for unexpected situations.


✔ Create custom exceptions only when needed


Don’t overuse them.


10. Try-with-resources (Modern Java Feature)


Introduced in Java 7 to automatically close resources.


try (FileInputStream fis = new FileInputStream("sample.txt")) {

    // Read file

} catch (IOException e) {

    e.printStackTrace();

}



The resource is closed automatically—no need for a finally block.


Summary


Exception handling in Java ensures programs remain stable and maintainable by:


Providing structured error handling (try-catch-finally)


Separating normal logic from error-handling logic


Preventing crashes due to unexpected runtime issues


Allowing graceful recovery


Mastering exception handling is essential for writing robust Java applications.

Learn Full Stack JAVA Course in Hyderabad

Read More

Java Collections Framework: List, Set, Map

Java Data Types and Variables Explained

Object-Oriented Programming in Java

☕ Core Java Concepts

Visit Our Quality Thought Institute in Hyderabad

Get Directions

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive