Command Palette

Search for a command to run...

Back to the lesson: Topic 7.1 — What Exceptions Are
Core Java · Example 1 of 3

Watch an exception travel up the stack

With a zero count, the 'finished' lines never print: each frame is abandoned as the exception passes through it.

An exception is an object that describes something that went wrong. When it is thrown, Java stops the current code, walks back up the chain of method calls looking for a matching catch, and if none is found the thread dies and prints a stack trace.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a program that calls Integer.parseInt("12a") inside a try block and prints the exception's simple class name and message.

02

Write three methods a(), b(), c() where c() throws new UnsupportedOperationException("not yet"). Catch it in main and print how many frames the stack trace has and the name of the top method.

03

Build an array of three Throwables (new OutOfMemoryError(), new java.io.IOException(), new NullPointerException()) and, for each, print whether a catch (Exception e) block would catch it.

Explain it without notes

01

What is an exception in Java, and what happens step by step when one is thrown?

02

What is the difference between Error, checked exceptions and unchecked exceptions?

03

How do you read a stack trace to find the bug?

04

Why are exceptions better than returning error codes, and what do they cost?

Watch an exception travel up the stack
Sign in to run this example in your browser.

Expected output

main starts
 average starts
  divide(90, 3) starts
  divide finished
 average finished
result: 30
 average starts
  divide(90, 0) starts
caught in main: java.lang.ArithmeticException: / by zero
main carries on