Exception Handling in Java
Real programs meet problems they can't prevent: a user types "abc" where a number belongs, a file is missing, the network drops, someone divides by zero. When Java hits a problem like that, it throws an exception: it stops the normal flow and creates an object describing what went wrong. If nothing catches it, the program crashes with a red error message. Exception handling is how you catch those problems and decide what to do instead: show a friendly message, try again, use a default, or report the error clearly.
Without Handling, Then with Handling
Here's what happens when nobody handles a problem:
public class Crash {
public static void main(String[] args) {
int qty = Integer.parseInt("abc");
System.out.println("This line never runs");
}
}Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:565)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at Crash.main(Crash.java:3)The program stops at line 3; the next line never runs. Now the same kind of work, with handling:
public class Recover {
public static void main(String[] args) {
String[] inputs = {"12", "abc", "0"};
for (String in : inputs) {
try {
int n = Integer.parseInt(in);
System.out.println("100 / " + n + " = " + (100 / n));
} catch (NumberFormatException e) {
System.out.println("Not a number: " + in);
} catch (ArithmeticException e) {
System.out.println("Can't divide by zero: " + e.getMessage());
}
}
System.out.println("Program continues");
}
}100 / 12 = 8
Not a number: abc
Can't divide by zero: / by zero
Program continuesHow it works
- Code that might fail goes inside
try { ... }. - For
"12", nothing goes wrong: both catch blocks are skipped. - For
"abc",parseIntthrows aNumberFormatException. The rest of thetryblock is skipped, and Java jumps to thecatchblock for that type. - For
"0", the division throws anArithmeticException, and its own catch block runs. - Either way, the loop and the program keep going.
Why Java Uses Exceptions
Older languages often reported errors with special return values like -1, which callers easily forgot to check. Exceptions are better in three ways:
| Benefit | What it means |
|---|---|
| Can't be silently ignored | An unhandled exception stops the program loudly, instead of carrying on with wrong data |
| Separates normal code from error code | The try block reads like the happy path; problems are handled in catch |
| Carries information | The exception's type, message and stack trace say what went wrong and where |
The Pieces You'll Learn
This chapter covers the whole toolkit, one lesson each:
| Keyword or idea | Job |
|---|---|
try, catch | Run risky code and handle problems |
finally | Code that runs whether or not something failed |
| try-with-resources | Close files and connections automatically |
throw | Signal a problem yourself |
throws | Declare which problems a method may pass to its caller |
| Custom exceptions | Your own exception types with clear names |
| Stack traces | Reading the error report to find the bug |
Common Mistakes
Catching an exception and doing nothing. An empty catch hides the bug; at least log it.
Using exceptions for normal decisions. Check if (list.isEmpty()) instead of waiting for an exception.
Catching Exception everywhere. Catch the specific types you can handle.
Interview Corner
What is an exception in Java?
An exception is an object representing an abnormal event that disrupts the normal flow of a program, such as invalid input, a missing file or division by zero. When one occurs, Java creates an exception object and throws it; the runtime then looks for a matching catch block up the call stack. If none is found, the thread terminates and the stack trace is printed.
What is exception handling, and why is it useful?
Exception handling is the mechanism of catching and responding to exceptions using try, catch, finally and related constructs. It lets a program recover from errors or fail with a clear message instead of crashing, keeps error-handling code separate from normal logic, and makes errors impossible to ignore silently.
Practice
- Easy: Ask for two numbers with
Scannerand print their quotient. Handle a non-number and a zero divisor with friendly messages. - Harder: Read prices from the array
{"120", "95.5", "free", "250"}, add up the valid ones asdoubles, and print how many were skipped.
Key Takeaways
Was this tutorial helpful?