Exception Handling in Java
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) —
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) —
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 —
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.
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 —
Explanation —
- When
checkAge(15)is called, the method detects that the age is less than 18. - The
throwkeyword manually raises anArithmeticException - Since there is no
try-catchblock, 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 —
Explanation —
- The
divide()method declares that it might throw anArithmeticExceptionusingthrowskeyword. - The
main()method callsdivide(), so it must handle the exception usingtry-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—
Key differences between throw and throws
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.
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.
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 —
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 —
The End Happy Coding!









