Handling Errors (try / catch)
try / catch lets your program handle errors gracefully instead of crashing.
What you will learn
- Understand what an exception is
- Catch errors with try / catch
- Keep programs running after a problem
When things go wrong
Sometimes code hits a problem at runtime (runtime simply means "while the program is actually running", as opposed to while you are writing or compiling it): dividing by zero, reading text that is not a number, or going past the end of an array. Java calls this an exception — an unexpected event that interrupts the normal flow. If you do nothing, the exception crashes your program.
Here is a crash waiting to happen:
int[] nums = {1, 2, 3};
System.out.println(nums[5]); // index 5 does not exist!Note: Output: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3 The program crashed because index 5 is past the end of a 3-item array. Nothing after this line would run.
Catching the error
Wrap risky code in a try block. If an exception happens, Java jumps to the catch block instead of crashing.
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0; // dividing by zero!
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Oops: cannot divide by zero.");
}
System.out.println("The program keeps going.");
}
}Note: Output: Oops: cannot divide by zero. The program keeps going. Dividing by zero would normally crash, but the catch block caught it and printed a friendly message. Crucially, the last line still ran — the program survived.
What happens, step by step
Following the program above in order, here is exactly how Java moves through a try / catch:
- Java enters the
tryblock and starts running the risky code line by line. - It reaches
10 / 0and an exception is thrown (here, anArithmeticException) — dividing by zero is not allowed. - Java stops the rest of the try block at once (so the
println(result)line never runs) and looks for a matchingcatch. - The
catch (ArithmeticException e)block matches, so Java runs it and prints the friendly message. Theeholds the error details. - The
try / catchis finished, so Java continues normally with the next line after it — printing "The program keeps going." The program survived instead of crashing.
The shape to remember
try— put the code that might fail here.catch (SomeException e)— runs only if that kind of error happens.e.getMessage()— gives details about what went wrong.finally(optional) — runs no matter what, perfect for clean-up.
Watch out: Do not catch errors and then ignore them silently (an empty catch block). At the very least print or log a message, so you know a problem happened.
Tip: Catch specific exceptions when you can (like ArithmeticException or NumberFormatException). It makes your code clearer than catching the general Exception, and you handle each problem properly.
Q. What is the main benefit of try / catch?
✍️ Practice
- Wrap
Integer.parseInt("abc")in a try / catch and print a friendly message when it fails. - Add a
finallyblock that prints Done whether or not an error happened.
🏠 Homework
- Write a program that reads a number with Scanner inside a try / catch, so typing letters shows a friendly message instead of crashing.