Sub topic 4
Catching Exceptions with try and catch
In the last chapters you saw that an exception stops normal program flow. If nothing handles it, the program crashes and prints a stack trace. This chapter shows how to handle an exception so your program can recover and keep running. The tool for this is the try and catch pair.
The Basic Shape
A try block is a block of code that might throw an exception. A catch block is a block of code that runs only if a matching exception is thrown inside the try block.
Here is the shape:
public class Shape {
public static void main(String[] args) {
try {
// code that might fail
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
// code that runs only if that failure happens
System.out.println("Bad index: " + e.getMessage());
}
}
}The words in parentheses after catch matter:
ArrayIndexOutOfBoundsExceptionis the exception type. The catch block only handles exceptions of this type or its subclasses.eis the catch parameter. It is a variable that holds the exception object that was thrown. You can name it anything, buteis the usual choice.
Running this prints:
Bad index: Index 5 out of bounds for length 3The program did not crash. The catch block handled the problem.
A Worked Example: Parsing a Number
Integer.parseInt turns text like "42" into the number 42. If the text is not a valid number, it throws a NumberFormatException.
public class ParseDemo {
public static void main(String[] args) {
try {
int n = Integer.parseInt("42x");
System.out.println("Parsed: " + n);
} catch (NumberFormatException e) {
System.out.println("Not a number: " + e.getMessage());
}
System.out.println("Program continues");
}
}Output:
Not a number: For input string: "42x"
Program continuesLook closely at what did not print. The line Parsed: ... never ran. Here is what happened, step by step:
- Java enters the try block.
Integer.parseInt("42x")throws aNumberFormatException.- Java stops the try block right there. It skips every line left in the try block.
- Java looks for a catch block whose type matches.
NumberFormatExceptionmatches. - The catch block runs and prints the message.
- Java continues with the first line after the whole try-catch statement.
If you change "42x" to "42", no exception is thrown. The try block finishes normally, the catch block is skipped, and you see Parsed: 42 then Program continues.
What You Can Do with the Exception Object
The catch parameter e is a normal object. Every exception has some useful methods:
| Method | What it gives you | Example result |
|---|---|---|
| `e.getMessage()` | A short text describing the problem | `For input string: "42x"` |
| `e.toString()` | The class name plus the message | `java.lang.NumberFormatException: For input string: "42x"` |
| `e.printStackTrace()` | Prints the full stack trace to the error output | Several lines showing where it happened |
| `e.getClass().getName()` | Just the exception's class name | `java.lang.NumberFormatException` |
getMessage() can return null for some exceptions, so do not assume it always has text. Printing e directly calls toString(), which is often clearer.
Recovering and Continuing in a Loop
Catching is most useful when you can do something sensible and move on. This program adds up a list of values and skips the bad ones:
public class SumValid {
public static void main(String[] args) {
String[] inputs = {"10", "abc", "25", "", "7"};
int total = 0;
int skipped = 0;
for (String text : inputs) {
try {
total += Integer.parseInt(text);
} catch (NumberFormatException e) {
System.out.println("Skipping bad value: \"" + text + "\"");
skipped++;
}
}
System.out.println("Total: " + total);
System.out.println("Skipped: " + skipped);
}
}Output:
Skipping bad value: "abc"
Skipping bad value: ""
Total: 42
Skipped: 2The try-catch sits inside the loop. Each pass through the loop gets its own chance to fail and recover. If you put the whole loop inside one try block instead, the first bad value would end the loop. "25" and "7" would never be added.
Catching a Parent Type
A catch block matches the named type and any subclass of it. NumberFormatException is a subclass of IllegalArgumentException, which is a subclass of RuntimeException. So this also catches it:
public class ParentCatch {
public static void main(String[] args) {
try {
Integer.parseInt("hello");
} catch (IllegalArgumentException e) {
System.out.println("Caught: " + e);
}
}
}Output:
Caught: java.lang.NumberFormatException: For input string: "hello"The object is still a NumberFormatException. Only the variable type is the parent. This is the same rule as normal inheritance: a parent-type variable can hold a child object.
When the catch Type Does Not Match
If the thrown exception does not match the catch type, the catch block does nothing. The exception keeps moving up to the caller, as if there were no try-catch at all.
public class WrongType {
public static void main(String[] args) {
try {
Integer.parseInt("oops");
} catch (ArithmeticException e) {
System.out.println("This never prints");
}
System.out.println("This never prints either");
}
}NumberFormatException is not an ArithmeticException, so nothing catches it. The program crashes with a stack trace, and neither print line runs.
Variable Scope: A Common Trap
A variable declared inside a try block exists only inside that block. This code does not compile:
try {
int n = Integer.parseInt("42");
} catch (NumberFormatException e) {
System.out.println("bad");
}
System.out.println(n); // error: cannot find symbol nTo use the value afterwards, declare the variable before the try block and give it a starting value:
public class ScopeFix {
public static void main(String[] args) {
int n = 0; // default if parsing fails
try {
n = Integer.parseInt("42");
} catch (NumberFormatException e) {
System.out.println("Bad input, using 0");
}
System.out.println("n = " + n);
}
}Output: n = 42. The starting value is needed. Without it, the compiler complains that n might not have been set, because the assignment could have failed.
Mistakes Beginners Often Make
- An empty catch block. Writing
catch (Exception e) { }hides the failure, and you will never know it happened. At the very least, print or log the exception. - Catching
Exceptioneverywhere. It catches far more than you meant, including bugs likeNullPointerException. Catch the specific type you expect. - A try block that is too large. When twenty lines sit in one try block, you cannot tell which one failed.
- Expecting the try block to resume. After the catch block runs, Java never goes back into the try block. It continues after the whole statement.
Later chapters build on this. You will see how to handle several types at once, how to run cleanup code with finally, and how to throw exceptions yourself.
Exercise
What does this program print? try { System.out.println("A"); int x = Integer.parseInt("12z"); System.out.println("B"); } catch (NumberFormatException e) { System.out.println("C"); } System.out.println("D");
Show answer
It prints A, C, D, each on its own line. "A" prints first. parseInt throws on "12z", so "B" is skipped. The matching catch block prints "C", and then execution continues after the try-catch and prints "D".
Exercise
A catch block is written as catch (RuntimeException e). Will it catch a NumberFormatException? Why?
Show answer
Yes. NumberFormatException is a subclass of IllegalArgumentException, which is a subclass of RuntimeException. A catch block matches its named type and every subclass of that type.
Exercise
Write a method static int parseOrDefault(String text, int fallback) that returns the parsed number, or returns fallback if the text is not a valid integer.
Show answer
static int parseOrDefault(String text, int fallback) { try { return Integer.parseInt(text); } catch (NumberFormatException e) { return fallback; } } For example, parseOrDefault("15", 0) returns 15 and parseOrDefault("x", 0) returns 0.