Command Palette

Search for a command to run...

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

Read the stack trace from code

Line numbers are left out on purpose so the output is stable. getLineNumber() gives them when you need them.

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?

Read the stack trace from code
Sign in to run this example in your browser.

Expected output

message: deep problem
  at Main.level3
  at Main.level2
  at Main.level1
  at Main.main