Java Exception Handling: try, catch and finally
A bill splitter crashes on a table with zero guests and table 9 never runs. try and catch keep it going, the exception travels back through the call stack to the matching catch, two catches handle 0 and "four", and finally prints the receipt either way.
What you will learn
- Explain what an exception is and why an uncaught one stops the program
- Wrap risky code in try and handle it in catch with getMessage
- Trace how an exception travels back up the call stack to a matching catch
- Use several catch blocks and a finally block that runs on both paths
Before you start
- Java methods and overloading
- Java scope, code blocks and the call stack
Sometimes a line simply can't finish, and an unhandled problem crashes the whole program. Exception handling lets your application deal with the problem and carry on.
One zero stops everything
package org.studyeasy.s03l19;
public class Ex01_BillCrash {
static int share(int bill, int guests) {
return bill / guests; // guests = 0: no answer exists
}
public static void main(String[] args) {
System.out.println("Table 4: " + share(120, 4));
System.out.println("Table 7: " + share(90, 0));
System.out.println("Table 9: " + share(60, 3)); // never runs
}
}
Table 4: 30
Exception in thread "main" java.lang.ArithmeticException: / by zero
at org.studyeasy.s03l19.Ex01_BillCrash.share(Ex01_BillCrash.java:5)
at org.studyeasy.s03l19.Ex01_BillCrash.main(Ex01_BillCrash.java:10)
Table 4 works. Table 7 has zero guests, and bill / guests can't finish (integer division by zero, as in operators). Java throws an exception: an object it creates when a line cannot finish, here an ArithmeticException with the message "/ by zero". Nothing catches it, so the program stops there, and table 9 never runs.
Catch it, keep going
package org.studyeasy.s03l19;
public class Ex02_CatchIt {
static int share(int bill, int guests) {
return bill / guests;
}
public static void main(String[] args) {
System.out.println("Table 4: " + share(120, 4));
try {
System.out.println("Table 7: " + share(90, 0));
System.out.println("Table 7 paid"); // skipped
} catch (ArithmeticException e) {
System.out.println("Table 7 skipped: " + e.getMessage());
}
System.out.println("Table 9: " + share(60, 3)); // still runs
}
}
Table 4: 30
Table 7 skipped: / by zero
Table 9: 20
The risky call goes inside try. If it fails, the catch block for that exception type runs, and e.getMessage() tells you why. The rest of the try block is skipped after the failing line, so "Table 7 paid" never prints. After the catch, the program carries on, and table 9 is served.
The type matters. Write catch (NumberFormatException e) instead and the ArithmeticException isn't caught: the program crashes as before.
The exception goes back to the caller
main calls share(90, 0) and a new frame goes on the call stack. The division can't finish, so Java creates the exception object. share has no catch, so its frame is removed and the exception goes back to main. There the type matches the catch, the catch runs, and the program continues.
Two ways to fail, two catches
package org.studyeasy.s03l19;
public class Ex03_MultiCatch {
public static void main(String[] args) {
String[] guests = {"4", "0", "four"}; // typed in by staff
for (String text : guests) {
try {
int count = Integer.parseInt(text);
System.out.println("Each pays " + 120 / count);
} catch (NumberFormatException e) {
System.out.println("'" + text + "' is not a number");
} catch (ArithmeticException e) {
System.out.println("Cannot split: no guests");
}
}
System.out.println("All tables done");
}
}
Each pays 30
Cannot split: no guests
'four' is not a number
All tables done
"four" spelled out makes parseInt throw a NumberFormatException; "0" makes the division throw an ArithmeticException. Java runs the first catch whose type matches, so each problem gets its own message, and the loop finishes every table. Delete the NumberFormatException catch and "four" crashes the program.
finally runs either way
package org.studyeasy.s03l19;
public class Ex04_Finally {
static void payTable(int bill, int guests) {
try {
System.out.println("Each pays " + bill / guests);
} catch (ArithmeticException e) {
System.out.println("Cannot split: no guests");
} finally {
System.out.println("Receipt printed"); // on BOTH paths
}
}
public static void main(String[] args) {
payTable(120, 4);
payTable(90, 0);
}
}
Each pays 30
Receipt printed
Cannot split: no guests
Receipt printed
With 4 guests the try succeeds and the catch is skipped. With 0 the catch handles it. The finally block runs both times. Even when the catch has the wrong type and the program crashes, "Receipt printed" still prints first. Use finally for clean-up that must always happen.
Recap
| Block | Runs when |
|---|---|
try | always starts; the rest is skipped once something is thrown |
catch (Type e) | only when that type is thrown; e.getMessage() gives the reason |
| several catches | one per kind of failure; the first match wins |
finally | on success and on failure |
You don't need to memorise the syntax; an AI can write a try/catch for you. What matters is knowing what each part does. Next: throwing your own exceptions in throw, throws and custom exceptions.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Java throw, throws, Checked vs Unchecked and Custom Exceptions
A deposit of -20 is fine for Java but wrong for the bank, so throw rejects it. An InsufficientFundsException declines Maria's 500 with "Short by 380.0", the stack trace shows withdraw, settle and main, and the compiler refuses a checked call nobody handles.
Java try-with-resources and Clean Error Handling
Put the resource in the brackets after try and Java closes it when the block ends. A LogFile that implements AutoCloseable prints Closed bills.log on success and, when share(90, 0) throws, before the catch runs. Plus four habits for clean errors.
