Tutorials Logic, IN info@tutorialslogic.com

Exception Handling in Java try, catch, finally: Causes and Fixes

try, catch, and finally

Exception handling should explain try, catch, finally, throw, throws, checked exceptions, unchecked exceptions, and the difference between handling and hiding a failure.

Use Java exceptions to separate successful results from failures, catch only where recovery or context is possible, and preserve the original cause when rethrowing.

Use try for risky code, catch for handling specific exceptions, and finally for cleanup that should run whether an exception occurs or not.

Basic Exception Handling

Basic Exception Handling
public class TryCatchDemo {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
            System.out.println(result);
        } catch (ArithmeticException ex) {
            System.out.println("Cannot divide by zero");
        } finally {
            System.out.println("Done");
        }
    }
}

Checked vs Unchecked Exceptions

Checked exceptions must be handled or declared. Unchecked exceptions extend RuntimeException and usually indicate programming mistakes or invalid inputs.

Type Examples Compiler Requires Handling?
Checked IOException, SQLException Yes
Unchecked NullPointerException, IllegalArgumentException No
Error OutOfMemoryError, StackOverflowError No; usually do not catch

throw and throws

throw creates and sends an exception. throws declares that a method may pass an exception to its caller.

throw Example

throw Example
class AgeValidator {
    static void validateAge(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative");
        }
    }
}

try-with-resources

Use try-with-resources for objects that must be closed, such as files, streams, and database resources.

try-with-resources - Java Example

try-with-resources - Java Example
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class FileReadDemo {
    public static void main(String[] args) throws IOException {
        String content = Files.readString(Path.of("notes.txt"));
        System.out.println(content);
    }
}

Handling Exceptions Without Hiding Bugs

A catch block should either recover, translate the error into a clearer domain response, or log and rethrow. Empty catch blocks are dangerous because they hide failures and make debugging harder.

  • Catch specific exceptions first.
  • Use finally or try-with-resources for cleanup.
  • Do not catch Exception unless you have a clear reason.
  • Preserve useful error details.

Recovering from Java errors without hiding them

Exception handling lets Java code respond to failures in a controlled way. try contains risky code, catch handles a specific exception, and finally runs cleanup logic whether the operation succeeds or fails. The aim is not to silence errors; the aim is to protect the program and give a useful recovery path.

Good exception handling starts by catching the right exception at the right level. A NumberFormatException near input parsing can show a helpful validation message. A database exception might need logging and a retry or user-friendly failure response. Catching Exception everywhere makes debugging harder because it hides what actually went wrong.

  • Catch specific exceptions before broad ones.
  • Use finally or try-with-resources for cleanup.
  • Do not ignore the exception object.
  • Show users helpful messages while preserving technical details for logs.

Parsing input with a specific catch block

Parsing input with a specific catch block
String input = "twenty";

try {
    int age = Integer.parseInt(input);
    System.out.println(age);
} catch (NumberFormatException ex) {
    System.out.println("Please enter age using digits only.");
}
Before you move on

Exception Handling in Java try, catch, finally: Causes and Fixes Mastery Check

4 checks
  • Catch the narrowest useful exception and order related catch clauses from specific to general.
  • Preserve the original cause when translating an exception at an API boundary.
  • Close resources with try-with-resources and verify suppressed exceptions when cleanup also fails.
  • Test the success path, expected failure path, propagation behavior, and required cleanup separately.

Core Java Questions Learners Ask

No. Use them for exceptional failures, not expected choices.

It avoids hiding unrelated bugs and lets the handler respond appropriately.

Cleanup that must run whether the operation succeeds or fails.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.