When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
Specifying the Exceptions Thrown by a Method
To specify that method can throw an exception, add a throws clause to the method declaration for the method. The throws clause comprises the throws keyword followed by a comma-separated list of all the exceptions thrown by that method. The clause goes after the method name and argument list and before the brace that defines the scope of the method.
Advantages of Exceptions
- Advantage 1: Separating Error-Handling Code from "Regular" Code. Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code.
- Advantage 2: Propagating Errors Up the Call Stack. A second advantage of exceptions is the ability to propagate error reporting up the call stack of methods.
- Advantage 3: Grouping and Differentiating Error Types. Because all exceptions thrown within a program are objects, the grouping or categorizing of exceptions is a natural outcome of the class hierarchy.
How to Throw Exceptions
- Exception handler
- Class: Defining Methods
- Class: Returning a Value from a Method
- Checked exceptions
- Runtime exceptions
- Unchecked exceptions
- Exceptions: Specifying the Exceptions Thrown by a Method
- Exceptions: Advantages of Exceptions
- The try Block
- The catch Blocks
- The finally Block
- The throw Statement
- Exceptions: How to Throw Exceptions
- The Queue Interface