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.

Handling exceptions with try/catch

Handling exceptions with try/catch - Java Tutorial

From the course: Java 8 Essential Training

Start my 1-month free trial

Handling exceptions with try/catch

- Whenever you write code that could potentially throw an exception at runtime, you can wrap that code or surround it in a try catch block. And I have code here that's going to throw an exception. This line of code on line 10 tries to get a character from an array but it uses the expression, chars.length, looking for an item in the length index instead of length -1. As we've seen previously, that's the wrong way to do it. And when I run the code, I get that exception, with an extension object that's an instance of the class, ArrayIndexOutOfBoundsException. Now to fix this, I'll wrap these two lines of code in a try catch block. I could type in the code, but IntelliJ IDEA can generate the right code for you. So I'll select those two lines of code then I'll go to the menu and I'll choose code, surround with. Then from the list that appears, I'll choose try/catch. That wraps the two lines of code that I selected inside a try block and then creates a catch block right underneath it. If…

Contents