Exception Handling in Java

Naveen AnamaneniUpdated · 5 min read

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:

Crash.java
public class Crash {
    public static void main(String[] args) {
        int qty = Integer.parseInt("abc");
        System.out.println("This line never runs");
    }
}
Terminal output
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:

An exception jumps straight to the matching catch; then the program carries on
Recover.java▶ Try it
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");
    }
}
Output
100 / 12 = 8
Not a number: abc
Can't divide by zero: / by zero
Program continues

How it works

  1. Code that might fail goes inside try { ... }.
  2. For "12", nothing goes wrong: both catch blocks are skipped.
  3. For "abc", parseInt throws a NumberFormatException. The rest of the try block is skipped, and Java jumps to the catch block for that type.
  4. For "0", the division throws an ArithmeticException, and its own catch block runs.
  5. 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:

BenefitWhat it means
Can't be silently ignoredAn unhandled exception stops the program loudly, instead of carrying on with wrong data
Separates normal code from error codeThe try block reads like the happy path; problems are handled in catch
Carries informationThe 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 ideaJob
try, catchRun risky code and handle problems
finallyCode that runs whether or not something failed
try-with-resourcesClose files and connections automatically
throwSignal a problem yourself
throwsDeclare which problems a method may pass to its caller
Custom exceptionsYour own exception types with clear names
Stack tracesReading 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

  1. Easy: Ask for two numbers with Scanner and print their quotient. Handle a non-number and a zero divisor with friendly messages.
  2. Harder: Read prices from the array {"120", "95.5", "free", "250"}, add up the valid ones as doubles, and print how many were skipped.

Quick check: Exception handling

4 questions
1What happens to the rest of a try block after an exception is thrown?
2What happens if no catch block handles an exception?
3What is an exception, technically?
4Where should you catch an exception?

Key Takeaways

Was this tutorial helpful?

Lesson 214 of 482