Try-Catch Lesson

Handling the Unexpected

Some errors aren't bugs in your code but are caused by unpredictable, external factors like user input or file issues. The `try-catch` block is Java's powerful tool for handling these "exceptional events" gracefully without crashing your program.

What is a `try-catch` Block?

A `try-catch` block allows you to isolate "risky" code that might cause a runtime error. If an error (an `Exception`) occurs, your program can "catch" it and execute a special block of code to handle the problem, rather than stopping completely.

The Anatomy of `try-catch`

  • `try` block: You place the code that might throw an exception inside this block.
  • `catch` block: This code only runs if an exception of a specific type occurs in the `try` block. It allows you to respond to the error.
  • `finally` block (Optional): This code is always executed, whether an exception happened or not. It's perfect for cleanup tasks like closing files.

A Practical Example: Handling Bad User Input

Let's look at a common scenario: converting a user's text input into a number. If the user types "hello" instead of "10", a `NumberFormatException` will occur.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
String ageString = scanner.nextLine();

try {
    // Risky code: This line might throw a NumberFormatException
    int age = Integer.parseInt(ageString);
    System.out.println("In 5 years, you will be " + (age + 5) + " years old.");
} catch (NumberFormatException e) {
    // This code only runs if the exception occurs
    System.out.println("Error: That was not a valid number!");
    System.out.println("Details: " + e.getMessage());
} finally {
    // This code always runs, perfect for cleanup
    scanner.close();
    System.out.println("Scanner has been closed.");
}
    

The `try-with-resources` Statement

For resources that need to be closed (like a `Scanner` reading from a file), Java provides a modern, cleaner syntax called `try-with-resources`. It automatically handles closing the resource for you, even if an error occurs, making a `finally` block unnecessary for this purpose.

// The FileReader is declared in the parentheses
try (FileReader reader = new FileReader("config.txt")) {
    // ... read from the file ...
    System.out.println("File read successfully.");
} catch (IOException e) {
    System.out.println("Error reading file: " + e.getMessage());
}
// The 'reader' is guaranteed to be closed here.
    

Test Your Knowledge

Question: In a `try-catch-finally` block, under what circumstances will the code inside the `finally` block be executed?