[!NOTE] Even if your code compiles perfectly, real-world problems will occur while the program is actually running. A user might try to upload a corrupted file, the database server might catch fire, or the network might partition.
When Java encounters a fatal error during runtime, it throws an Exception. If you do not explicitly catch and handle that exception, your entire application will instantly crash.
The Try-Catch Block
The try-catch block allows you to anticipate potential failures and provide a safe fallback mechanism instead of a hard crash.
public class InputExample {
public static void main(String[] args) {
try {
// 1. The DANGEROUS code goes in the 'try' block
int[] myNumbers = {1, 2, 3};
// FATAL ERROR! Index 10 does not exist!
System.out.println(myNumbers[10]);
// This line is NEVER reached because the error immediately jumps to 'catch'
System.out.println("Execution continues...");
} catch (Exception e) {
// 2. The FALLBACK code goes in the 'catch' block
System.out.println("Something went wrong, but the app survived!");
System.out.println("Developer Error Log: " + e.getMessage());
}
}
}
The 'finally' Block
Often, you open an expensive system resource (like a database connection or a file stream) in your try block. If an error occurs halfway through, the code jumps to catch, and your command to close that connection is bypassed!
The finally block executes no matter what happens. Even if a try block successfully returns, or a catch block catches an error, the finally block is guaranteed to execute before the method finishes.
Scanner scan = new Scanner(System.in);
try {
int age = scan.nextInt();
System.out.println("Valid age: " + age);
} catch (Exception e) {
System.out.println("Please enter a valid number!");
} finally {
// This code will always execute! Prevents memory leaks!
scan.close();
System.out.println("Scanner closed successfully.");
}
[!TIP] Catching Specific Errors: Instead of catching a generic
Exception e, you should catch specific exceptions likeNullPointerExceptionorFileNotFoundException. This allows you to write custom fallback logic depending on exactly why the code failed.
Handling Exceptions Without Hiding Bugs
Exception handling is not about making errors disappear. It is about deciding which failures the program can recover from, which failures should be logged, and which failures should stop the operation immediately.
Catch Specific Exceptions First
try {
int value = Integer.parseInt(input);
System.out.println("Parsed: " + value);
} catch (NumberFormatException e) {
System.out.println("Please enter a valid whole number.");
}
This is better than catching generic Exception because it documents the exact failure you expect. Catching everything can accidentally hide programming mistakes.
Log for Developers, Message for Users
A user-friendly message should explain what the user can do next. A developer log should keep technical detail such as exception type, message, and stack trace.
Common Mistakes
- Catching
Exceptioneverywhere and continuing as if nothing happened. - Leaving catch blocks empty.
- Showing raw stack traces directly to end users.
- Using exceptions for normal control flow, such as checking if a list is empty.
Mini Practice
Write a method that converts a string into an integer. If parsing fails, show a clean message and return a default value. Then update it to log the original exception message for developers.
Practice Lab: Safe Number Parser
Practice handling bad runtime input without hiding the failure.
- Create a method
parseMark(String input). - Use
Integer.parseInt(input)inside a try block. - Catch
NumberFormatExceptionand return-1. - Print a user-friendly message when parsing fails.
- Test inputs like
"85","abc", and"".
Goal: Catch a specific expected exception and keep the program flow controlled.
Revision Checkpoint
- Exception: Runtime problem represented as an object.
try: Holds risky code.catch: Handles a specific failure.finally: Runs cleanup code.- Best habit: Catch specific exceptions and avoid empty catch blocks.
Before the quiz: Explain what should be shown to users and what should be logged for developers.