What is an exception?
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)An exception is a problem that happens while a program is running, like splitting a bill among 0 friends. If nothing handles it, Java stops the program and prints an error report.
A problem while the program runs
A bill-split app divides ₹900 among the friends, but friends is 0. The code is correct Java, yet the division has no answer, so Java throws an exception: it reports the problem and stops the program.
Example 1 · Dividing a bill by 0 friends
public class BillSplit { public static void main(String[] args) { int bill = 900; int friends = 0; System.out.println("Bill: " + bill); int share = bill / friends; System.out.println("Each pays: " + share); }}Bill: 900 Exception in thread "main" java.lang.ArithmeticException: / by zero at BillSplit.main(BillSplit.java:6)
What this code does
- Line 5 runs normally, so
Bill: 900is printed first. - Line 6,
bill / friends, divides anintby 0. There is no answer, so Java throwsArithmeticExceptionand the program stops there. Each paysnever prints, even though line 7 is fine: after an exception, nothing more runs.
Reading the error report
The report Java prints is called a stack trace. It looks scary, but you need only three things from it: the exception's name, its message and the line where it happened.
Example 2 · An exception inside a method
public class AvgCrash { static int average(int total, int count) { return total / count; }
public static void main(String[] args) { System.out.println(average(240, 3)); System.out.println(average(240, 0)); }}80 Exception in thread "main" java.lang.ArithmeticException: / by zero at AvgCrash.average(AvgCrash.java:3) at AvgCrash.main(AvgCrash.java:8)
What this code does
- The first call works and prints
80. - The first
atline is where the problem happened: line 3, insideaverage. - The next
atline shows who called that method:main, on line 8. Read the report from the top down.
java.lang. in front of the name only says which group of Java's own classes it comes from. Skip it while reading.Compile error or exception?
A missing ; and a division by 0 both stop you, but at different times. A compile error is found by javac before the program runs; an exception happens while it runs, which is why exceptions are also called runtime errors.
int friends = 0;System.out.println("Bill split") // compile error: ';' expectedint share = 900 / friends; // compiles, then throws ArithmeticExceptionClassify
Compile error or exception?
Tap a problem, then tap when Java finds it: before the program runs, or while it runs.
Next step
Check your understanding
8 quick questions