CS 239 - Exceptions


Exception
A situation that arises during program execution that is erroneous or out of the ordinary.
Exception handler
The code in a catch clause of a try statement, executed when a particular type of exception is "thrown".

Take a look at the code example, ExceptV1.java.

How many statements in this code could cause a run-time error. Note: This program compiles properly. However, no matter the input, this program will always provide a run-time error. Why?

Take a look at the code example, ExceptV2.java. The error that will always cause a problem has been corrected. And if proper input is given, the program will run to completion and give accurate results. What potential run-time errors still exist? Note: We have switched the values to be double instead of int.

Information found in an exception. Sample.rtf.

Exception handling

  1. Prevention - In many cases it is better to anticipate exceptions and write your code in such a way as to prevent them from occurring. See ExceptV3.java.
  2. Handling - In other cases, where an exception is truly exceptional and a mechanism for elegantly handling potential program failure is desired, we can use the exception handling mechanism of java.

Syntax - See Page 535 - Formal specification of the try statement.

try
{
   statementBlock;
}
catch(ExceptionName variable)
{
   statementBlock;
}
finally
{
   statementBlock;
}

The try statement contains the code that we are executing. If an action does not cause an exception, control returns to the statement following the try/catch block. If an action causes an exception, then the code in the catch block executes. See ExceptV3.java.

Exceptions may be "thrown" to their next higher calling method until handled. See Propagation.java and ExceptionScope.java L&L page 539 - 540.

NOTE: You may have multiple catch blocks associated with a single try block. Each must be identified by class name.