This module discusses a key part of the Java language and libraries known as exceptions.
Exceptions are Java's way of reporting and working with errors. They allow programmers to explicitly and formally define a control flow for errors, and they separate error detection from error handling.
By the end of the module, you should be able to:
- Describe why exceptions occur
- Catch exceptions
- Throw exceptions
- Make your own exceptions
- Be able to use the finally keyword
The term "exception" means
exceptional condition and is an occurrence that alters the normal program flow. Many factors can lead to exceptions, including
- hardware failures,
- resource exhaustion, and
- improper coding.
When an exceptional event occurs in Java, an exception is said to be "thrown." The code that is responsible for doing something about the exception is called an "exception handler" and it "catches" the thrown exception. Exception handling works by transferring the execution of a program to an appropriate exception handler when an exception occurs.
For example, if you call a method that opens a file but the file cannot be opened, execution of that method will stop, and the code that you wrote to deal with this situation will be run. Therefore, we need a way to tell the
JVM what code to execute when a certain exception happens.
To do this, we use the try and catch keywords. The try is used to define a block of code in which exceptions may occur. This block of code is called a
guarded region (which really means "risky code goes here").
One or more catch clauses match a specific exception (or group of exceptions) to a block of code that handles it.