It is not a matter of IF but WHEN things will go wrong in a computer program. Sometimes there are bugs, errors of one form or another. There are also unforeseen use cases. You can never assume a computer program is perfect. Exception-Handling helps us to catch erroneous events and devise means of correcting them. We discuss this topic here since exception-handling can take more code than should be put into the main line of execution. In such cases, a method in an exception-handling class should be called. Exception handling mechanisms allow a program to continue executing, instead of terminating it abruptly, even if an error occurs in the program.
10.4 Handling Exceptions Within a Program Exception Propagation: Searching for a Catch Block
Restrictions on the try/catch/finally Statement
There are several important restrictions that apply to Java’s exceptionhandling mechanism. We’ll describe these in more detail later in this
chapter.
- A try block must be immediately followed by one or more catch clauses and a catch clause may only follow a try block.
- A throw statement is used to throw both checked exceptions and unchecked exceptions, where unchecked exceptions are those belonging to RuntimeException or its subclasses. Unchecked exceptions need not be caught by the program.
- A throw statement must be contained within the dynamic scope of a try block, and the type of Exception thrown must match at least one of the try block’s catch clauses. Or the throw statement must be contained within a method or constructor that has a throws clause for the type of thrown Exception.