Unit 3: Version Control and Troubleshooting
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.
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.
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.");
}
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.
Question: In a `try-catch-finally` block, under what circumstances will the code inside the `finally` block be executed?