ProLesson 5.2Intermediate3 min readUpdated 30 October 2026
try, catch and finally
Handle exceptions with try and catch, catch several types, understand finally, and avoid the classic finally-and-return trap.
try and catch let you handle an exception instead of letting it stop your program. You put risky code in try, and the code that deals with the problem in catch.
01The basic shape
TryCatch.java
public class TryCatch {
static int parseQuantity(String input) {
try {
int qty = Integer.parseInt(input);
System.out.println("Parsed " + qty);
return qty;
} catch (NumberFormatException e) {
System.out.println("Not a number: " + input);
return 1; // sensible default
}
}
public static void main(String[] args) {
System.out.println(parseQuantity("3"));
System.out.println(parseQuantity("three"));
}
}Parsed 3 3 Not a number: three 1
When an exception is thrown inside try, Java jumps straight to the matching catch. The rest of the try block is skipped.
Loading the rest of the lesson…