Exceptions in Java
(Basics, advanced concepts, and real API examples)
Nik Lumi
Copyright 2022 Nik Lumi
All rights reserved.
This book or any portion thereof
may not be reproduced or used in any manner whatsoever
without the express written permission of the publisher
except for the use of brief quotations in a book review.
If you would like to use this book for other purposes,
please contact nik.lumi.contact@gmail.com
Published in the United States of America
First Published, January 2022
Contents
Preface
T he concept of a software exception was introduced into programming in the early 60s. Since then, it has been adopted by many languages and has evolved significantly.
It is generally accepted that exceptions help separate different concerns in programming and therefore improve manageability of code. While very few people will deny the usefulness of exceptions, there is ongoing debate on how they should be used.
This book covers the basics of Java exceptions, advanced concept, and best practices, and gives a historical overview of how exception handling in Java was and is approached. In addition, this book provides examples of real APIs with analysis on how these APIs approach and handle exceptions.
This book assumes that the reader is familiar with the basics of the Java programming language, and is able to write, compile and execute a simple program. It also assumes that the reader is able to read and understand code excerpts.
We hope you both enjoy and learn from this book.
1. His tory
W e all know well what an exceptional situation is in real life. It is when something unexpected happens that we must deal with. For most of us, it happens many times a day and often more frequently than expected.
You leave your garage and two blocks later your car alternator starts making a loud noise. What should you do? Drive home? Drive directly to your mechanic? Can your car make it? You must quickly answer these questions that run through your head and then you must make the corresponding decisions.
At a workplace be it McDonalds or an airplane cockpit people face these types of questions and often are given instructions on how to proceed.
In the IT world, these types of situations are extremely common.
The mechanism known as exception handing is supposed to solve these problems, or at least make them easier to solve. Exception handling is a systemic approach to exceptional situations.
Interrupts
The notion of interrupts, introduced in mid 1950s, is not exactly the same as modern exception handling but is close to it.
Interrupts refer to both hardware and software. In both cases there is a request to the processor to interrupt (or delay, or postpone use any word you like) its current activity and handle this specific situation. After the specific situation is handled, the processor may resume its interrupted activity .
Lisp, Ada, COBOL, and others
Lisp was the first language that introduced software exception handling in a way similar to what we know today. It introduced key words like ERRSET, ERR, CATCH, and THROW. Their meanings and usages were similar to what they are today.
Computer languages like Ada, COBOL, Object Pascal, and others quickly adopted the concept. Its implementation may vary from language to language, but the core idea is the same.
C/C++
C did not have exceptions.
In 1985, C++ was released as an object-oriented extension of C. In addition to other things, exception handling was an integral part of the program. C++ added the power of object-oriented programming to it.
C++ is the language from which the architects of Java borrowed exception handling semantics. With C++, one may declare an exception in a method signature, but its usage will not be enforced by the compiler.
The architects of Java, as we will see later, tried to take things one step further. They added the idea of checked exceptions. This means that some exceptions may become a part of a method signature, thus requiring special handling.
Normal & Abnormal
The whole concept behind exception handling (and its conceptual predecessors) is that there are two ways that a program may be executed.
1) The program executes normally; all language elements work as they should; or
2) The program executes abnormally; there is not enough memory allocated, a null value is passed instead of a reference to a valid object, or there is no file by the location passed by the caller.
The separation of normal and abnormal execution sounds simple and intuitive, and normally does not cause controversy.
However, some experts go further and support the idea of a separation of abnormal behavior further into two categories - recoverable abnormal and unrecoverable abnormal. Recoverable abnormal conditions can be intercepted by the program itself and tried for recovery. Unrecoverable abnormal however would normally require termination of the execution and human intervention. What is recoverable and what is not recoverable could have easily been given to the programmers discretion to be decided based upon each particular situation, however, the fathers of Java made it possible to enforce mandatory handling of recoverable abnormal as a part of the rigid programming contract. Many experts criticize this decision. Who is right and who is wrong will be discussed in a later chapter.
Return & Goto
Exceptions can be described as alternative return values, and exception handling as an alternative return mechanism. But, contrary to a return statement, they may return a call not to the next level up the call stack, but to an arbitrary level higher, bypassing all intermediate checks for the return value. So, another way to describe them is a non-local conditional goto.
Exceptions & OOP
Objects have very convenient semantics. In OOP languages (including Java) the information about exceptional behavior can be extracted, encapsulated, and separated from the normal flow. In addition to information about where, when, and how the exceptional conditions took place, information can be transparently added to the object that describes the exceptional condition.
In summary, in OOP languages exceptions combine the power of non-local transition of control with object-oriented semantics.
2. Ess entials
I n this chapter we explain the basic mechanism that the Java programming language offers for exception handling. This chapter intentionally does not cover what is considered right or wrong with regards to using exceptions; this will be covered in later chapters. The purpose of this chapter is to describe the technical aspects of exception handling provided in Java.
Types
Java is an object-oriented language, which means classes play an important role in it and its multiple concepts are represented in the form of classes. Exceptions are no pun intended not an exception to this rule.
Therefore, every exception is an object of a class with some specific behavior .
Hierarchy
There are several important classes in the exceptions hierarchy that are treated specially by the JVM.
Throwable
The java.lang.Throwable class is at the root of the Java exception hierarchy. Any exception used in the Java programming language should be its subclass.
The class has five constructors.
public Throwable()
public Throwable(String message)
public Throwable(String message, Throwable cause)
protected Throwable(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)
public Throwable(Throwable cause)