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:
- programming errors (e.g. trying to call a method on a null object);
- unexpected environmental errors (e.g. an expected setup file not being found, or the system running out of memory);
- expected errors such as invalid user input.
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
- methods such as file access methods, string parsing methods etc declare that they can throw
certain exceptions— effectively indicating that certain errors are likely to occur;
- the Java Virtual Machine, while executing your program, can also interrupt the normal program flow
by "throwing" an exception, e.g. if you attempt to access a null object reference or invalid array index;
- blocks of code can be accompanied by error handlers called catch clauses: when an exception
is thrown, the program flow will "jump" to the surrounding catch clause that can handle the error in question.
(Here are some examples of exceptions thrown by the Java Virtual Machine.)
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.