Try-Catch Block in Java
A try-catch block is a safety net around code that might fail. You put the risky statements in try, and in catch you say which kind of problem you're ready for and what to do about it. If the problem happens, Java jumps straight to your catch; if it doesn't, the catch is skipped as if it weren't there. Watching that jump happen line by line is the best way to understand it.
Step by Step
public class SplitBill {
static void split(int bill, String people) {
try {
int n = Integer.parseInt(people);
System.out.println("Each pays Rs. " + bill / n);
} catch (NumberFormatException e) {
System.out.println("'" + people + "' isn't a number of people");
}
System.out.println("Done with " + people);
}
public static void main(String[] args) {
split(1200, "4");
split(1200, "four");
}
}Each pays Rs. 300
Done with 4
'four' isn't a number of people
Done with fourHow it works
- With
"4", both lines intryrun, thecatchis skipped, and the method continues after it. - With
"four",parseIntthrows aNumberFormatException. Theprintlnafter it intryis skipped. Java looks for acatchthat matches the exception's type, finds one, and runs it. - After the
catch, execution continues normally with"Done with four".
What the Exception Object Tells You
The variable in catch (NumberFormatException e) is the exception object itself. Its methods describe the problem:
public class Inspect {
public static void main(String[] args) {
try {
Integer.parseInt("12a");
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
System.out.println(e);
System.out.println(e.getClass().getName());
}
}
}For input string: "12a"
java.lang.NumberFormatException: For input string: "12a"
java.lang.NumberFormatException| Method | Returns |
|---|---|
getMessage() | The detail message |
toString() (or printing e) | The class name and the message |
getClass().getName() | The exception's class |
printStackTrace() | Prints the full stack trace to the error stream |
getCause() | The exception that caused this one, if any |
Variables and Scope
A variable declared inside try exists only inside try. If you need the value afterwards, declare the variable before the try and give it a default:
public class Scope {
public static void main(String[] args) {
int qty = 1;
try {
qty = Integer.parseInt("x3");
} catch (NumberFormatException e) {
System.out.println("Using the default quantity");
}
System.out.println("Quantity: " + qty);
}
}Using the default quantity
Quantity: 1Common Mistakes
An empty catch block. The problem disappears silently; at least print or log it.
Declaring the variable inside try and using it after. It's out of scope; declare it before.
Catching a type that the code can't throw. For checked exceptions, it's a compile error ("is never thrown in body of corresponding try statement").
Practice
- Easy: Read an age as text, parse it in a
try, and print "Invalid age" for bad input. Use a default of 0. - Harder: Write
static int[] parseAll(String[] items)that returns the numbers it could parse and prints a message for each item it skipped.
Key Takeaways
Was this tutorial helpful?