Exceptions
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
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
public Object pop() {
Object obj;
if (size == 0) {
throw new EmptyStackException();
}
obj = objectAt(size - 1);
setObjectAt(size - 1, null);
size--;
return obj;
} Exception is always thrown with the throw statement.
The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class.
Related concepts
- Errors
- 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
Semantic portal