1️⃣

14.1 Exception Handling and Try/Catch

Exception Handling

When writing and running Java code, you have probably run into many errors in the process. Compiler errors(missing semicolons, etc.), Runtime Errors(like a bad or unusable input), and many others.

When such an error happens, Java normally stops what it’s doing and gives you an error message. In other words, Java is throwing an exception.

However, if you don’t want Java to stop for an exception, or you want to test a block of code for possible errors, you can use exception handling. This involves writing specific code that "handles" exceptions, and it will only be executed if something in the program goes wrong and the exception occurs.

Try and Catch

The try statement allows you to test a block of code for errors, and if it finds an error, the code inside the catch block will run. Here’s the syntax:

try {
			int[] b = {2, 8, 9, 10, 14}
			System.out..println(n[15]);
} catch(Exception e) {
			System.out.println("Oops, an error occurred");
}

The array does not have a 15th index, and so it would normally report an out of bounds error. However, the try/catch block causes the console to display “Oops, an error occurred”.

You can also use the Exception e itself in your catch block. For example, if you want to see what error occurred, use e.toString() in your print statement, which is the String representation of your Exception.

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.