From the course: Java 8+ Essential Training: Objects and APIs

Unlock the full course today

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

Create multiple catch blocks

Create multiple catch blocks - Java Tutorial

From the course: Java 8+ Essential Training: Objects and APIs

Start my 1-month free trial

Create multiple catch blocks

- [Instructor] When you use structured exception handling in Java, you're looking for particular kinds of exceptions. In this code that I demonstrated in the previous video, I have two bits of code that might generate an exception. The first bit of code is correct right now, it extracts a value out of an array using an index of cars dot length minus one. Because of the zero-based offset, that means give me the last item in the array. If I change that, so I'm looking for just the length, that generates an array index out of bounds exception. If I fix that expression, my flow can now get to this bit of code that tries to call a method from a null object. And that generates a null pointer exception. Right now though, I only have a catch block for the array index out of bounds exception. To fix that, you can add multiple catch sections. I'll start by typing the keyword catch, then inside the parenthesis, I'll pass in the type of the exception I'm looking for, null pointer exception. I'll…

Contents