Sub topic 4
Catching Exceptions with try and catch
An exception is an object Java creates when something goes wrong while your program runs. If nothing handles it, the program stops and prints an error. In this chapter, you will learn to catch an exception so your program can keep running.
The try and catch blocks
A try block is a section of code that might cause an exception. You put the risky code inside it.
A catch block is code that runs only if a certain kind of exception happens in the try block. It says which exception type it handles, and it gives that exception a name, often e.
Here is the basic shape:
public class Shape {
public static void main(String[] args) {
try {
// risky code goes here
int[] numbers = new int[2];
numbers[5] = 1;
} catch (ArrayIndexOutOfBoundsException e) {
// this runs only if that exception happens
System.out.println("Bad index: " + e.getMessage());
}
}
}A worked example
The method Integer.parseInt turns text like "42" into the number 42. If the text is not a 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");
}
}When you run it, you see:
Not a number: For input string: "42x"
Program continuesHere is what happens, step by step:
- Java starts the try block and calls
Integer.parseInt("42x"). - The text
"42x"is not a number, soparseIntthrows aNumberFormatException. - Java skips the rest of the try block. The line
"Parsed: "never prints. - Java finds a catch block that matches the exception type and runs it.
- After the catch block, the program continues on the next line.
If you change "42x" to "42", no exception happens. The try block finishes, Java skips the catch block, and you see Parsed: 42 then Program continues.
What the exception object gives you
The variable e in the catch block is the exception object. It has useful methods:
| Method | What it gives you |
|---|---|
| `e.getMessage()` | A short text that describes the problem |
| `e.toString()` | The exception's class name plus the message |
| `e.printStackTrace()` | A full report of where the error happened |
Exercises
Exercise
In ParseDemo, why does the line "Parsed: " never print when the input is "42x"?
Show answer
When parseInt throws the exception, Java leaves the try block right away and skips every remaining line in it. It jumps straight to the matching catch block.
Exercise
What does this program print? int x = 0; try { x = Integer.parseInt("7"); System.out.println("A"); } catch (NumberFormatException e) { System.out.println("B"); } System.out.println(x);
Show answer
It prints "A" and then "7". "7" is a valid number, so no exception is thrown and the catch block is skipped.