Exceptions
Navigate Exceptions topic: ) |
Topics: |
The ideal time to catch an error is at compile time, before you even try to run the program. However, not all errors can be detected at compile time. The rest of the problems must be handled at run time through some formality that allows the originator of the error to pass appropriate information to a recipient who will know how to handle the difficulty properly.
Improved error recovery is one of the most powerful ways that you can increase the robustness of your code. Error recovery is a fundamental concern for every program you write, but it's especially important in Java, where one of the primary goals is to create program components for others to use. To create a robust system, each component must be robust. By providing a consistent error-reporting model using exceptions, Java allows components to reliably communicate problems to client code.
Flow of code execution
[edit | edit source]In Java, there are two main flows of code executions.
- Normal main sequential code execution, the program doing what it meant to accomplish.
- Exception handling code execution, the main program flow was interrupted by an error or some other condition that prevent the continuation of the normal main sequential code execution.
- Exception
- Exceptions are Java's way of error handling. Whenever an unexpected condition occurs, an exception can be thrown with an exception object as a parameter. It means that the normal program control flow stops and the search for a
catch
block begins. If that is not found at the current method level the search continues at the caller method level, until a matchingcatch
block is found. If none is found the exception will be handled by the JVM, and usually the java program terminates.
- When a
catch
"matching" block is found, that block will be executed, the exception object is passed to the block as a parameter. Then normal program execution continues after thecatch
block. See Java exception handling syntax.
- Exception Object
- This is the object that is "thrown" as a parameter from the error, and passed to the
catch
block. Exception object encapsulates the information about the error's location and its nature. All Exception objects must be inherited from thejava.lang.Throwable
. See the UML diagram below.
Figure 6.1: Java exception classes
|
- Matching rule
- A thrown exception object can be caught by the
catch
keyword and specifying the exception object's class or its super-class.
- Naming convention
- It is good practice to add Exception to all exception classes. The name of the exception should be meaningful, and should represent the problem. For example,
CustomerNotFoundException
may indicate that a customer was not found.