Catching Exceptions

Created By: Geoffrey Challen
/ Updated: 2022-10-05

We'll spend the rest rest of the week learning about Java exceptions. Errors are a normal part of programming, and Java provides nice ways for handling them. Let's learn more!

Exceptions: When Things Go Wrong

It's natural to make mistakes when you write computer programs. But even well-designed programs may encounter errors!

Imagine the following scenario. You design an app that prompts the user to enter a number that you plan to use in a mathematical calculation. What you receive is a String, so you need to convert it to an Integer. What could go wrong? Let's find out!

Walk through problems that can emerge when we try to parse an number using Integer.parseInt. Don't get to try-catch, since we'll do that next.

What is happening here? Let's examine the documentation for Integer.parseInt to find out.

Examine the documentation for Integer.parseInt and point out that it can throw an exception.


In Java, when code that we write or call encounters an error, it can throw an Exception. Over the next few lessons we'll explore Java's error-handling mechanisms, including types of exceptions and how to design and throw them in our own code.

But let's start at looking at how to handle exceptions that we might encounter. To do this we use a new Java programming construct: try-catch. Let's see how that works!

Demonstrate how to use a single try-catch block.

try-catch consists of two or more code blocks. First, the try block, containing the code that might throw an exception. Second, one or more catch blocks that handle various kinds of exceptions that the code might throw. Let's look at some code that can generate several kinds of exceptions and see how to handle them:

Show how to use multiple try-catch blocks to handle different kinds of exceptions.

Show how to complete the homework problem above. Feel free to cover multiple approaches!

Exception Control Flow

One of the more difficult parts of exceptions is understanding how code flow changes when an exception is thrown. When an exception is thrown, Java jumps into the first enclosing catch block. This might be in that method, or in calling method, or even in the caller's caller or higher up. Let's look at an admittedly contrived example:

Show how exceptions affect control flow. Put the try-catch block in several different spots and show what happens.

Don't worry if this doesn't make perfect sense yet—we'll get lots of practice with this over the next few days!

Show how to complete the homework problem above. Feel free to cover multiple approaches!

Show how to complete the homework problem above. Feel free to cover multiple approaches!

More Practice

Need more practice? Head over to the practice page.