Sitemap
DEEPAK MAURYA

DEEPAK MAURYA

Software Engineer

Exception Handling in Java

5 min readFeb 16, 2026

--

Press enter or click to view image in full size

Exception handling is a mechanism in Java that helps manage runtime errors and maintain the normal flow of a program.

Consider the following example (If you run the program, it will crash without exception handling) —

Press enter or click to view image in full size

Importance of Exception Handling

Exception handling is essential for several reasons —

  • Prevents crashes: Ensures that a single error doesn’t stop the entire program.
  • Improves debugging: Helps in identifying and resolving errors quickly.
  • Encapsulates error handling: Separates normal code from error-handling code.
  • Ensures proper resource management: Prevents memory leaks by ensuring files and connections are properly closed.

Consider the following example (with Exception Handling) —

Press enter or click to view image in full size
Press enter or click to view image in full size

Mechanism to handle Exception (Try-Catch Block)

Java provides the try-catch mechanism to handle exceptions —

  • try block: Contains the code that may throw an exception.
  • catch block: Handles the exception if it occurs.
import java.util.*;
try {
// Code that might cause an exception
}
catch (ExceptionType e) {
// Code to handle the exception
}

Consider the following example —

Press enter or click to view image in full size

finally Block (closing Resources)

The finally block is always executed, whether an exception occurs or not. It is used to close resources such as files, database connections, or network sockets. However, it is not necessary to add the finally block in the try-catch ladder.

Press enter or click to view image in full size

throw and throws Keywords

Java provides two important keywords — throw and throws — for handling exceptions effectively. While they might sound similar, they serve different purposes in exception handling.

1. throw — Manually Throwing an Exception

  • The throw keyword is used inside a method or block to explicitly throw an exception.
  • It is typically used when we want to indicate that an error has occurred due to invalid input or some exceptional condition.
  • The throw statement is followed by an instance of an exception.
// Syntax
import java.util.*;
throw new ExceptionType("Error Message");

Note that The ExceptionType must be a subclass of Throwable (like ArithmeticException, NullPointerException, or a user-defined exception).

Get DEEPAK MAURYA’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s consider an example where we prevent a person from voting if their age is below 18 —

Press enter or click to view image in full size

Explanation —

  • When checkAge(15) is called, the method detects that the age is less than 18.
  • The throw keyword manually raises an ArithmeticException
  • Since there is no try-catch block, the program terminates abruptly.

2. throws — Declaring an Exception

  • The throws keyword is used in a method signature to indicate that the method might throw an exception.
  • It does not handle the exception but forces the caller to handle it.
  • This is useful when a method relies on external resources like files, databases, or network connections.
// Syntax
import java.util.*;
returnType methodName() throws ExceptionType {
// Method code that might throw an exception
}

The method does not handle the exception internally it leaves the responsibility to the caller.

Let’s consider a method that performs division but might cause an ArithmeticException —

Press enter or click to view image in full size

Explanation —

  • The divide() method declares that it might throw an ArithmeticException using throws keyword.
  • The main() method calls divide(), so it must handle the exception using try-catch.
  • When division by zero occurs, the exception is caught and handled without stopping the program.

Let’s consider another example that might cause an IndexOutOfBoundsException—

Press enter or click to view image in full size

Key differences between throw and throws

Press enter or click to view image in full size

Custom Exceptions

In Java, custom exceptions (also known as user-defined exceptions) allow developers to define their own exception classes. This is useful when the built-in Java exceptions (ArithmeticException, IOException, etc.) do not fully describe the error conditions specific to an application.
By creating a custom exception, we can provide more meaningful error messages and handle specific cases more effectively.

Press enter or click to view image in full size

Real-Life Example of Exception Handling

In real-world applications, exceptions frequently occur due to external dependencies, such as file handling, database access, or network communication. Proper exception handling ensures that the program does not crash and provides a meaningful error message to the user.

Say in our program, one needs to read the content of other file (that may not exist). In such cases, file handling exception must be implemented properly.

Press enter or click to view image in full size

Checked & Unchecked Exceptions

Checked Exceptions

These are exceptions that the compiler forces you to handle using try-catch or declare using throws (e.g., IOException, SQLException).
Example —

Press enter or click to view image in full size

Unchecked Exceptions

These occur at runtime and do not require explicit handling. They are usually due to logical errors in the code (e.g., NullPointerException, ArithmeticException).
Example —

Press enter or click to view image in full size

The End Happy Coding!

--

--