From the course: Java 8 Essential Training

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Creating multiple catch blocks

Creating multiple catch blocks - Java Tutorial

From the course: Java 8 Essential Training

Start my 1-month free trial

Creating multiple catch blocks

- When you wrap a bit of code in a try block, you can actually have more than one catch section. Each catch block should look for a specific exception, and then your code path will change depending on which exception is generated. In this project, MultiCatch, I still have code in place that's generating an exception. I'm looking for a particular character from a character array. But this expression, chars.length, will look at an index greater than the available number of items. And when I run the code, I'll hit my catch block, and print the StackTrace. To make it clear that that's what's happening, I'm going to comment out this line of code by pressing ctrl + / on Windows or cmd + / on Mac. Then I'll replace it with custom output, and I'll simply display my own custom message. "Array index problem!" Then I'll run the code again. And I see my custom message is displayed. So that confirms that the try catch block is working. Now I'm going to add a bit more code down here, still within…

Contents