Finally Block and Throw/Throws in java : A Complete Guide for Developers
Java finally block example with try-catch ensuring resource cleanup
In Java exception handling, the finally block and the throw/throws keywords are essential for writing reliable and maintainable code. They work alongside try
and catch
blocks to ensure proper error handling and resource management.
A finally block is an optional block in Java that follows a try
or catch
block. It contains code that will always execute, regardless of whether an exception occurs.
Use Cases:
Closing database connections
Releasing file handles
Cleaning up resources
Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} finally {
System.out.println("Execution completed.");
}
The throw keyword is used to explicitly throw an exception from a method or block of code.
Example:
public void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or above");
}
}
The throws keyword is used in a method signature to declare the exceptions a method might throw.
Example:
public void readFile(String fileName) throws IOException {
FileReader file = new FileReader(fileName);
}
Feature | throw | throws |
---|---|---|
Usage | Used inside method body | Declared in method signature |
Purpose | To explicitly throw exception | To declare possible exceptions |
Exceptions | Single exception at a time | Multiple exceptions possible |
Use finally to close resources and avoid leaks.
Use throw for custom error messages.
Always declare throws for checked exceptions.
Avoid overusing generic exceptions for better debugging.
The finally block ensures code execution in all scenarios, while throw and throws give you fine control over exception handling in Java. Mastering these concepts helps you build more reliable and maintainable applications.