Lesson 31 of 34

Exceptions: Handling Errors

10 min 30 XP

When an error (exception) happens while a program runs, it crashes. Put risky code inside try and handle the error in catch. finally always runs.

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

You can raise an exception yourself with throw, for example when a method receives a bad value.

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

Checked exceptions (like IOException) must be handled at compile time; unchecked ones (RuntimeException) need not be. Interviews love this difference.

Challenge

+30 XP

Read two values as text (sc.next()), convert them with Integer.parseInt and print the first divided by the second. Print "Invalid number" if either isn't a number and "Cannot divide by zero" when dividing by 0. Input: 20 4 → Output: 5

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.