3.1. Introduction

In Java, an exception is an event that occurs during the execution of a program that encounters an error or some kind of exceptional situation.

Note

Exceptions happen at runtime. Errors while compiling your programs are syntax errors - not exceptions.

You may have the impression that an exception always leads directly to a program crash and an obscure error message on the screen. For these reasons, you likely spent a lot of time on previous programming assignments attempting to avoid exceptions. In this tutorial, you will see that it is almost always better to let exceptions occur and then properly handle them instead of trying to avoid them.

We will demonstrate that exceptions, when used properly, can lead to cleaner code that has fewer bugs. You will see that exceptions are a way of passing a message from one method to another to indicate that something unexpected happened. Exceptions can be both informative and useful and should be handled (properly) instead of avoided.