Java Exceptions


While writing Java programs, it’s common to run into unexpected conditions such as dividing a number by zero, accessing an invalid array index, or trying to read a file that doesn’t exist. These situations are called exceptions.
An exception is an event that interrupts the normal flow of the program. In Java, exceptions help us handle such events gracefully without crashing the application.

For example, instead of a program stopping suddenly, Java allows you to catch the error, show a user-friendly message, and continue execution safely. Exception handling is one of the key features that makes Java robust and reliable.

What Is an Exception?

An exception is an error that occurs during program execution. It is represented by an object in Java that contains details about the error, like its type and cause.
When an exception occurs, the Java Virtual Machine (JVM) creates an exception object and hands it to the runtime system. If the exception isn’t handled, the program stops.

Example:

public class Example {
    public static void main(String[] args) {
        int a = 5;
        int b = 0;
        int result = a / b; // This will throw an exception
        System.out.println("Result: " + result);
    }
}

This program will throw an ArithmeticException because dividing by zero is not allowed.

Types of Exceptions in Java

Java categorizes exceptions into three main types:

1. Checked Exceptions

These are exceptions that the compiler checks during compile-time. If not handled properly, the program won’t compile.
Example: IOException, SQLException, FileNotFoundException.

2. Unchecked Exceptions

These occur during runtime. The compiler doesn’t check for them, so they must be handled manually.
Example: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException.

3. Errors

Errors are not the same as exceptions. They indicate serious problems that usually cannot be recovered from, such as OutOfMemoryError or StackOverflowError.

Exception Hierarchy in Java

All exceptions in Java are part of a class hierarchy that begins with the Throwable class.

Object
 └── Throwable
      ├── Exception
      │    ├── IOException
      │    └── SQLException
      └── Error
           ├── StackOverflowError
           └── OutOfMemoryError

Under the Exception class, there are both checked and unchecked exceptions.

Handling Exceptions in Java

Java provides a structured way to handle exceptions using the following keywords:

  1. try – Block of code where you suspect an error might occur.

  2. catch – Block that handles the exception if one occurs.

  3. finally – Block that always executes, whether an exception is thrown or not.

  4. throw – Used to manually throw an exception.

  5. throws – Declares exceptions in method signatures.

Example of try-catch Block

public class TryCatchExample {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[5]); // Invalid index
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output:

Error: Index 5 out of bounds for length 3

Here, the program doesn’t crash because the exception is handled using a try-catch block.

Using Multiple Catch Blocks

You can handle different types of exceptions separately by using multiple catch blocks.

public class MultiCatchExample {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            int result = numbers[2] / 0;
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero.");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Invalid array index.");
        }
    }
}

The finally Block

The finally block is used for code that should always execute, like closing files or releasing resources.

public class FinallyExample {
    public static void main(String[] args) {
        try {
            int a = 10 / 2;
            System.out.println("Result: " + a);
        } catch (Exception e) {
            System.out.println("Error occurred.");
        } finally {
            System.out.println("This block always executes.");
        }
    }
}

The throw and throws Keywords

  • throw: Used to manually throw an exception inside a method or block.

  • throws: Declares that a method can throw an exception, allowing the caller to handle it.

Example:

public class ThrowExample {
    static void checkAge(int age) {
        if (age < 18) {
            throw new ArithmeticException("Access denied - You must be at least 18 years old.");
        } else {
            System.out.println("Access granted.");
        }
    }

    public static void main(String[] args) {
        checkAge(15);
    }
}

Custom Exceptions

You can also create your own exception by extending the Exception class.

Example:

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

public class CustomExceptionExample {
    static void checkAge(int age) throws InvalidAgeException {
        if (age < 18)
            throw new InvalidAgeException("Not eligible to vote.");
        else
            System.out.println("Eligible to vote.");
    }

    public static void main(String[] args) {
        try {
            checkAge(16);
        } catch (InvalidAgeException e) {
            System.out.println("Caught Exception: " + e.getMessage());
        }
    }
}

Best Practices for Exception Handling

  1. Use specific exceptions instead of generic ones like Exception.

  2. Don’t ignore exceptions—always handle them properly.

  3. Avoid using exceptions for normal program flow.

  4. Release resources in a finally block or use try-with-resources.

  5. Always provide meaningful messages in custom exceptions.

Summary of the Tutorial

In this tutorial, you learned what exceptions are, their types, and how to handle them effectively using try-catch, finally, throw, and throws. You also saw how to create custom exceptions to handle specific conditions. Proper exception handling makes Java programs more stable, secure, and easier to maintain.


Practice Questions

  1. Write a Java program that performs division between two integers. Use a try-catch block to handle the case when the divisor is zero.

  2. Create a Java program that reads an element from an array. Handle ArrayIndexOutOfBoundsException when an invalid index is entered.

  3. Write a Java program that takes user input for a file name and handles FileNotFoundException if the file doesn’t exist.

  4. Create a program that uses multiple catch blocks to handle both ArithmeticException and NullPointerException.

  5. Write a Java program that always prints a closing message using a finally block, whether an exception occurs or not.

  6. Create a Java program that manually throws an exception using the throw keyword when a user enters a negative number.

  7. Write a program that defines a custom exception InvalidAgeException to check if the entered age is above 18.

  8. Create a Java method that declares an exception using the throws keyword and handles it in the main method.

  9. Write a program that reads data from a file using BufferedReader and uses a try-with-resources statement to handle exceptions automatically.

  10. Create a Java program that generates and catches a NumberFormatException when trying to convert a non-numeric string to an integer.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top