Useful JavaExtra· 30 min read

Handling Errors (try / catch)

try / catch lets your program handle errors gracefully instead of crashing.

What you will learn

  • Understand what an exception is
  • Catch errors with try / catch
  • Keep programs running after a problem

When things go wrong

Sometimes code hits a problem at runtime (runtime simply means "while the program is actually running", as opposed to while you are writing or compiling it): dividing by zero, reading text that is not a number, or going past the end of an array. Java calls this an exception — an unexpected event that interrupts the normal flow. If you do nothing, the exception crashes your program.

Here is a crash waiting to happen:

This throws an exception and stops the program
int[] nums = {1, 2, 3};
System.out.println(nums[5]);   // index 5 does not exist!

Note: Output: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3 The program crashed because index 5 is past the end of a 3-item array. Nothing after this line would run.

Catching the error

Wrap risky code in a try block. If an exception happens, Java jumps to the catch block instead of crashing.

try / catch handles the error gracefully
public class Main {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;     // dividing by zero!
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("Oops: cannot divide by zero.");
        }
        System.out.println("The program keeps going.");
    }
}

Note: Output: Oops: cannot divide by zero. The program keeps going. Dividing by zero would normally crash, but the catch block caught it and printed a friendly message. Crucially, the last line still ran — the program survived.

What happens, step by step

Following the program above in order, here is exactly how Java moves through a try / catch:

  1. Java enters the try block and starts running the risky code line by line.
  2. It reaches 10 / 0 and an exception is thrown (here, an ArithmeticException) — dividing by zero is not allowed.
  3. Java stops the rest of the try block at once (so the println(result) line never runs) and looks for a matching catch.
  4. The catch (ArithmeticException e) block matches, so Java runs it and prints the friendly message. The e holds the error details.
  5. The try / catch is finished, so Java continues normally with the next line after it — printing "The program keeps going." The program survived instead of crashing.

The shape to remember

  • try — put the code that might fail here.
  • catch (SomeException e) — runs only if that kind of error happens.
  • e.getMessage() — gives details about what went wrong.
  • finally (optional) — runs no matter what, perfect for clean-up.

Watch out: Do not catch errors and then ignore them silently (an empty catch block). At the very least print or log a message, so you know a problem happened.

Tip: Catch specific exceptions when you can (like ArithmeticException or NumberFormatException). It makes your code clearer than catching the general Exception, and you handle each problem properly.

Q. What is the main benefit of try / catch?

Answer: try / catch lets you respond to an exception (with a message or fallback) instead of letting it crash the whole program.

✍️ Practice

  1. Wrap Integer.parseInt("abc") in a try / catch and print a friendly message when it fails.
  2. Add a finally block that prints Done whether or not an error happened.

🏠 Homework

  1. Write a program that reads a number with Scanner inside a try / catch, so typing letters shows a friendly message instead of crashing.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →