LearnFrenzy
Sign in Take a free test

Exception Handling · Lesson 29 of 42

try, catch, finally and the Exception Hierarchy

5 min read Updated Nov 7, 2026 Saurabh Samir

Real programs meet problems they can't prevent: a file is missing, the network drops, a user types "ten" instead of 10. Java reports these as exceptions – objects that describe what went wrong. Handling them well is the difference between an app that crashes and one that shows a helpful message and carries on.

In this lesson

  • What happens when an exception is thrown
  • try, catch, multi-catch and finally
  • Reading a stack trace
  • The exception hierarchy

An uncaught exception

public class Main {
    public static void main(String[] args) {
        System.out.println("Start");
        int[] marks = {80, 90};
        System.out.println(marks[2]);        // no index 2
        System.out.println("End");           // never reached
    }
}

Output

Start
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2

When the JVM can't continue, it throws an exception. If nothing catches it, the thread stops and Java prints the exception with a stack trace such as:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
	at Main.main(Main.java:5)

Read it top to bottom: the exception type, the message, then each at line shows a method call, newest first, with the file and line number.

try and catch

public class Main {
    public static void main(String[] args) {
        String[] inputs = {"42", "forty-two", "0"};
        for (String in : inputs) {
            try {
                int n = Integer.parseInt(in);
                System.out.println("100 / " + n + " = " + 100 / n);
            } catch (NumberFormatException e) {
                System.out.println("'" + in + "' is not a number");
            } catch (ArithmeticException e) {
                System.out.println("Cannot divide by zero");
            }
        }
        System.out.println("Program continues");
    }
}

Output

100 / 42 = 2
'forty-two' is not a number
Cannot divide by zero
Program continues

When the try block throws

  1. Exception thrownthe rest of the try block is skipped
  2. Check catch blocks in orderthe first matching type wins
  3. Run that catchhandle, log or recover
  4. Continue after try/catchthe program keeps running

Multi-catch and order

public class Main {
    public static void main(String[] args) {
        Object[] tests = {"12", null, "x"};
        for (Object t : tests) {
            try {
                String s = (String) t;
                System.out.println(Integer.parseInt(s.trim()) * 2);
            } catch (NullPointerException | NumberFormatException e) {   // one handler, two types
                System.out.println("Bad input: " + e.getClass().getSimpleName());
            } catch (RuntimeException e) {                              // broader type last
                System.out.println("Something else: " + e.getMessage());
            }
        }
    }
}

Output

24
Bad input: NullPointerException
Bad input: NumberFormatException

Common mistake: catching Exception first

Catch blocks are checked top to bottom. A catch (Exception e) before catch (NumberFormatException e) makes the second unreachable, and the compiler reports an error. Put specific types first, general types last.

finally

A finally block runs whether the try block succeeds, throws or even returns. It's for clean-up: closing files, releasing locks, logging.

public class Main {
    static int process(String s) {
        try {
            System.out.println("  try: parsing " + s);
            return Integer.parseInt(s);
        } catch (NumberFormatException e) {
            System.out.println("  catch: invalid");
            return -1;
        } finally {
            System.out.println("  finally: always runs");
        }
    }

    public static void main(String[] args) {
        System.out.println("result " + process("7"));
        System.out.println("result " + process("x"));
    }
}

Output

  try: parsing 7
  finally: always runs
result 7
  try: parsing x
  catch: invalid
  finally: always runs
result -1

Interview angle

"Does finally run if the try block returns?" Yes – it runs before the method actually returns. The only common cases where it doesn't run are System.exit() or the JVM crashing. Never return from inside finally: it silently swallows any exception.

The exception hierarchy

Everything that can be thrown

Throwable

  • Errorserious JVM problems – OutOfMemoryError, StackOverflowError. Don't catch.
  • Exception (checked)IOException, SQLException – the compiler makes you handle or declare them
  • RuntimeException (unchecked)NullPointerException, IllegalArgumentException, ArithmeticException – usually bugs
ExceptionTypical cause
NullPointerExceptioncalling a method on a null reference
ArrayIndexOutOfBoundsExceptionindex < 0 or ≥ length
NumberFormatExceptionparsing text that isn't a number
ClassCastExceptioncasting to the wrong type
IllegalArgumentExceptiona method received a bad argument
IllegalStateExceptiona method was called at the wrong time
IOException (checked)file or network problems

Helpful NullPointerException messages

public class Main {
    public static void main(String[] args) {
        String city = null;
        try {
            System.out.println(city.length());
        } catch (NullPointerException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output

Cannot invoke "String.length()" because "<local1>" is null

Modern Java tells you exactly which value was null (with -g debug info, IDEs show the variable name instead of <local1>).

Practice

Try it yourself

  1. Write safeDivide(a, b) that returns a message instead of crashing when b is 0.

    Show solution
    public class Main {
        static String safeDivide(int a, int b) {
            try {
                return a + " / " + b + " = " + (a / b);
            } catch (ArithmeticException e) {
                return "Cannot divide " + a + " by zero";
            }
        }
    
        public static void main(String[] args) {
            System.out.println(safeDivide(10, 3));
            System.out.println(safeDivide(10, 0));
        }
    }

    Output

    10 / 3 = 3
    Cannot divide 10 by zero

Quick check

Does finally run when the catch block itself throws?

Yes, finally still runs; the new exception then propagates.

Should you catch OutOfMemoryError?

Generally no – Errors signal serious JVM problems your code can't fix.

In which order should catch blocks be written?

Most specific first, most general (Exception) last.

Summary

  • An uncaught exception stops the thread and prints a stack trace – read it top to bottom.
  • Use try/catch (specific first), multi-catch for shared handling, finally for clean-up.
  • Throwable → Error (don't catch) and Exception → checked exceptions + RuntimeException (unchecked).

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links