Java Exception Handling Explained: A Complete How-To Guide

Arkadipta KunduArkadipta Kundu
5 min read

Handling exceptions is an essential part of writing robust and error-free Java applications. Without proper exception handling, a small runtime error can crash an entire program. Java provides a structured approach to managing exceptions, ensuring that applications run smoothly even when unexpected errors occur.

In this guide, we'll cover everything you need to know about exception handling in Java, including types of errors, exception hierarchy, try-catch, throw vs throws, custom exceptions, and best practices.


πŸ”Ή 1. Types of Errors in Java

Before diving into exceptions, it's important to understand three main types of errors in Java:

1️⃣ Compile-Time Errors

These errors occur during compilation due to incorrect syntax or missing elements.

βœ… Example (Syntax Error):

System.out.println("Hello); // ❌ Missing closing quote causes a compile-time error

βœ”οΈ Solution: Java’s compiler detects and reports these errors, so you must fix them before running the program.


2️⃣ Logical Errors (Bugs)

The program runs without crashing, but produces incorrect results due to incorrect logic.

βœ… Example (Logic Error):

int result = 2 + 2; // Expecting 4, but mistakenly coded as 5

βœ”οΈ Solution: Debugging and testing help identify and fix logical errors.


3️⃣ Runtime Errors (Exceptions)

These errors occur during execution and may stop the program abruptly if not handled properly.

βœ… Example (Division by Zero - ArithmeticException):

int a = 10 / 0; // ❌ ArithmeticException: Division by zero

βœ”οΈ Solution: Use exception handling to catch such errors and prevent program crashes.


πŸ”Ή 2. What are Exceptions in Java?

An exception is an unexpected event that occurs during program execution, disrupting the normal flow. Java provides a built-in way to handle exceptions, ensuring programs remain stable.

πŸ” Why Handle Exceptions?

βœ”οΈ Prevents application crashes in critical systems (e.g., banking, medical software).
βœ”οΈ Improves user experience (graceful error messages instead of abrupt crashes).
βœ”οΈ Ensures smooth execution by allowing the program to recover.


πŸ”Ή 3. Exception Handling in Java (Try-Catch Mechanism)

Java provides the try-catch block to handle exceptions and prevent program termination.

βœ… Basic Syntax of Try-Catch

try {
    // Code that may cause an exception
} catch (ExceptionType e) {
    // Handle the exception
}

βœ… Example: Handling Division by Zero

try {
    int result = 10 / 0; // 🚨 Throws ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
}

πŸ› οΈ How It Works?

1️⃣ Code inside try executes first.
2️⃣ If an exception occurs, Java jumps to the catch block.
3️⃣ If no exception occurs, the catch block is skipped.


πŸ”Ή 4. Handling Multiple Exceptions

A program may throw different exceptions, and Java allows handling them separately using multiple catch blocks.

βœ… Example: Handling Multiple Exceptions

try {
    int[] arr = new int[5];
    arr[10] = 50; // 🚨 ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
    System.out.println("Arithmetic Error");
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Array Index Error");
} catch (Exception e) {
    System.out.println("Some other error occurred");
}

βœ”οΈ Order of Catch Blocks:
πŸ”Ή Specific exceptions first (e.g., ArrayIndexOutOfBoundsException).
πŸ”Ή General exceptions last (Exception is the parent of all exceptions).


πŸ”Ή 5. Exception Hierarchy in Java

Java exceptions follow this class hierarchy:

Object  
β”‚  
└── Throwable  
    β”œβ”€β”€ Exception (Handleable)  
    β”‚   β”œβ”€β”€ IOException  
    β”‚   β”œβ”€β”€ SQLException  
    β”‚   β”œβ”€β”€ RuntimeException (Unchecked)  
    β”‚       β”œβ”€β”€ ArithmeticException  
    β”‚       β”œβ”€β”€ NullPointerException  
    β”‚       β”œβ”€β”€ ArrayIndexOutOfBoundsException  
    β”‚  
    └── Error (Non-recoverable)  
        β”œβ”€β”€ OutOfMemoryError  
        β”œβ”€β”€ StackOverflowError

πŸ”Ή 6. throw vs throws in Java

βœ… throw (Manually Throw an Exception)

Used inside a method to generate an exception.

public void divide(int a, int b) {
    if (b == 0) {
        throw new ArithmeticException("Cannot divide by zero");
    }
    System.out.println(a / b);
}

βœ… throws (Declares Exceptions in a Method)

Used in the method declaration to indicate possible exceptions.

public void readFile() throws IOException {
    FileReader file = new FileReader("data.txt");
}

βœ”οΈ Key Difference:

  • throw is used inside a method to generate exceptions.

  • throws declares exceptions a method might throw.


πŸ”Ή 7. Creating Custom Exceptions

When built-in exceptions don’t fit, we can create custom exceptions.

βœ… Step 1: Create Custom Exception Class

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

βœ… Step 2: Use Custom Exception

public class Main {
    public static void checkAge(int age) throws MyException {
        if (age < 18) {
            throw new MyException("Age must be 18 or above");
        }
    }

    public static void main(String[] args) {
        try {
            checkAge(16);
        } catch (MyException e) {
            System.out.println(e.getMessage());
        }
    }
}

πŸ”Ή 8. Best Practices for Exception Handling

βœ”οΈ Use specific exceptions instead of Exception class.
βœ”οΈ Log exceptions properly instead of just printing.
βœ”οΈ Use finally block for cleanup (closing files, databases).
βœ”οΈ Avoid empty catch blocks (catch (Exception e) {}).
βœ”οΈ Don’t use exceptions for normal program flow.


πŸ”Ή 9. Real-World Use Cases

1️⃣ Banking Application (InsufficientBalanceException)

if (balance < amount) {
    throw new InsufficientBalanceException("Insufficient funds!");
}

2️⃣ File Handling in Web Applications (IOException)

public void readFile(String filename) throws IOException {
    FileReader file = new FileReader(filename);
}

3️⃣ Database Connectivity (SQLException)

try {
    Connection con = DriverManager.getConnection(DB_URL, USER, PASS);
} catch (SQLException e) {
    System.out.println("Database connection failed!");
}

🎯 Conclusion

βœ”οΈ Java provides try-catch, throw, throws, and finally for exception handling.
βœ”οΈ Understanding checked vs unchecked exceptions is crucial.
βœ”οΈ Custom exceptions improve error specificity.

In upcoming articles, I’ll expand on these topics in more detail. Follow me for more Java content! πŸš€πŸ”₯

0
Subscribe to my newsletter

Read articles from Arkadipta Kundu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Arkadipta Kundu
Arkadipta Kundu

I’m a Computer Science undergrad from India with a passion for coding and building things that make an impact. Skilled in Java, Data Structures and Algorithms (DSA), and web development, I love diving into problem-solving challenges and constantly learning. Right now, I’m focused on sharpening my DSA skills and expanding my expertise in Java development.