Finally Block and Throw/Throws in java : A Complete Guide for Developers

8/15/2025

Java finally block example with try-catch ensuring resource cleanup

Go Back

Finally Block and Throw/Throws In Java: A Complete Guide for Developers

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.


Java finally block example with try-catch ensuring resource cleanup

Finally Block

What is a Finally Block?

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.");
}

Throw Keyword

What is Throw?

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");
    }
}

Throws Keyword

What is Throws?

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);
}

Key Differences Between Throw and Throws

Featurethrowthrows
UsageUsed inside method bodyDeclared in method signature
PurposeTo explicitly throw exceptionTo declare possible exceptions
ExceptionsSingle exception at a timeMultiple exceptions possible

Best Practices

  • 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.


Final Thoughts

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.

 

Table of content