Exceptions and error handling in Java

Exceptions are a means to control error flow within a program. During the course of execution, your program may encounter errors for various reasons. A program will typical encounter various types of error, including:

Writing a complex program would be tedious if we needed to worry about such errors with every line of code: for example, if we had to check whether an object reference was null every single time we tried to access it, or if we had to check for an error condition after every single call to read a byte from a file. If you've programmed in a low-level language such as C, you'll be aware that you often do need to check for invalid pointers or error result codes after many simple standard library functions.

In a language such as Java, exceptions make error handling less tedious. Exceptions work as follows:

Exceptions therefore allow errors to be handled by shared error handling code, with more structured program flow, and without having to check for and micromanage error conditions after every individual line of code! We continue on the next page with an introduction to exceptions in Java.


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.