- Forward


Exceptions
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • The Problem:
    • Your method can't handle the values its been given
  • One Example:
    • A calculation that results in a negative price
  • One Solution:
    • Return a "special value"
Motivation (cont.)
Back SMYC Forward

An Example that Uses a Special Value

javaexamples/exceptions/PriceCalculator.java
 
Questions
Back SMYC Forward
  • What "special value" would you return for a method that fails while converting a String into a double?
    • Since all double values are legitimate return values there is no special value that can be used.
  • Is it always safe to return a "special value"?
    • No because you have to rely on the caller behaving properly in response (e.g., check for -1 in the previous example).
  • What else might we do to "signal" the caller that a special situation has arisen?
    • One could use an alternative return mechanism.
Exceptions - An Alternative Return Mechanism
Back SMYC Forward
  • Returning from Within a Method:
    • Normal Return - drop out of the method or use a return statement (with or without a value to return)
    • Alternative Return - Use a throw statement (which must pass back a Throwable object)
  • Handling a Return from a Method:
    • Normal Return - The method evaluates to the returned value (which can be used in an expression like any other value) and processing continues
    • Alternative Return - The caller must indicate what code should be executed on return (and how the Throwable should be used)
The Signature of a Method with Both Return Mechanisms
Back SMYC Forward
  • Normal Return:
    • The declaration of the method includes a return type (or void)
  • Alternative Return:
    • The declaration of the method includes a throws clause (that specifies the exception)
A Method with Both Return Mechanisms
Back SMYC Forward

In the following example, a throw statement is used for an alternative return and the return statement is used for a normal return.

javaexamples/exceptions/EmailAddress.java (Fragment: getHost)
 
Calling a Method that Uses Both Return Mechanisms
Back SMYC Forward
  • Normal Return:
    • A try block is used to indicate the code that should be executed when the method returns normally
  • Alternative Return:
    • A catch block (which is passed a Throwable) is used to indicate the code that should be executed when the method returns "abnormally"
The try-catch Statement
Back SMYC Forward
  • Syntax Click here for information. :
    • try {statement...} catch(exception name) {[statement]...}
  • Including the finally Clause:
    • try {statement...} [catch(exception name) {[statement]...}] finally {[statement]...}
    • The finally block is executed regardless of which try or catch block is executed.
The try-catch Statement (cont.)
Back SMYC Forward

Continuing the Earlier Example

javaexamples/exceptions/EmailProcessor.java
 
The try-catch Statement (cont.)
Back SMYC Forward

An Example with a Loop

javaexamples/exceptions/GradeProcessor.java
 
A Closer Look at the catch Portion
Back SMYC Forward
  • An Example:
    • catch(NumberFormatException nfe) { total += DEFAULT; }
  • What's Going On?
    • An operation or method is going to "throw" a NumberFormatException object that this statement is going to "catch" and name nfe.
    • This is not unlike a method with a single formal parameter.
Nerd Humor
Back SMYC Forward
Bonding
/imgs
(Courtesy of xkcd)
Re-Throwing Exceptions
Back SMYC Forward
  • An Observation:
    • A particular method may not be able to handle the "abnormal" return
    • Example: When a method that does a calculation would need to prompt for another input
  • An Alternative to try-catch
    • Re-throw the exception (i.e., "let someone else handle it") and specify that this is the case (i.e., include a throws clause in the declaration)
Re-Throwing Exceptions (cont.)
Back SMYC Forward

An Example

javaexamples/exceptions/Divider.java
 
Handling Re-Thrown Exceptions
Back SMYC Forward

An Example

javaexamples/exceptions/DividerDriver.java
 
Catch or Re-Throw?
Back SMYC Forward
  • A Design Question:
    • I'm calling a method that can throw an exception. Should I catch it or re-throw it?
  • The General Answer:
    • If "you" can handle the exception (e.g., use a default value or correct the mistake) then "you" should
    • Otherwise, assume that whoever called "you" will know how to handle it and re-throw it
Things to Avoid in Catch Blocks
Back SMYC Forward
  • "Never" Print in a catch Block:
    • If the application uses the console, the message will interrupt the normal flow of the user interface
    • If the applications doesn't use the console (e.g., uses a GUI), the message will be lost
  • What About Debugging?
    • While debugging it is often helpful to temporarily print in catch blocks (but it is better to use a logger)
  • What About main()?
    • In small applications it is sometimes permissible to print in catch blocks that are in the main() method
A Common Mistake
Back SMYC Forward

Beginning programmers often make the following mistake when told that a method must throw an exception. For example, if they are told that the method they are writing must throw a NumberFormatException they add a throws NumberFormatException clause to the method declaration and do the following.

try { d = Double.parseDouble(s); } catch (NumberFormatException nfe) { throw new NumberFormatException(); // throw nfe; is also bad }

Instead you should add a throws NumberFormatException clause to the method declaration and do the following.

d = Double.parseDouble(s);

The only reason to include a throw statement in a catch block is if a different exception must be thrown.

Exception Handling with Nested Blocks
Back SMYC Forward

The following two fragments have very different behavior.

javaexamples/exceptions/NestedBlockExample.java (Fragment: 0)
 
javaexamples/exceptions/NestedBlockExample.java (Fragment: 1)
 
Handling Multiple Exceptions
Back SMYC Forward
  • A Question:
    • Can a method return "abnormally" in more than one way?
  • The Answer:
    • Yes, a method can throw more than one exception
  • The Caller:
    • Can catch multiple exceptions
    • Can catch some exceptions and re-throw others
Handling Multiple Exceptions
Back SMYC Forward

An Example

javaexamples/exceptions/Calculator.java
 
Nested try-catch Blocks
Back SMYC Forward
  • A Question:
    • Can you tell which call to parseInt generated the exception in the previous example?
  • Handling These Situations:
    • You can nest try-catch statements
Nested try-catch Blocks (cont.)
Back SMYC Forward

An Example

javaexamples/exceptions/CalculatorNested.java
 
Two Additional Issues
Back SMYC Forward
  • Debugging:
    • All Exception objects have a printStackTrace() method that can be used during debugging (but only during debugging)
  • The main() Method
    • The main() method can re-throw exceptions
    • If it does, the application will terminate
Some "Familiar" Runtime Exceptions
Back SMYC Forward
  • The Exceptions:
    • ArithmeticException
    • IndexOutOfBoundsException
    • NegativeArraySizeException
    • NullPointerException
  • The Result:
    • In the past, an exception caused your application to terminate
    • Now you know you can catch or re-throw it
Overuse
Back SMYC Forward
  • A Common Mistake:
    • Beginning programmers often catch or re-throw exceptions without thinking (e.g., "The submissions system says there's an ArrayIndexOutOfBoundsException so I'll fix it by adding a try-catch block.")
  • An Important Guideline:
    • Don't use exception handling where other techniques can be applied easily (e.g., don't attempt to access a non-existent element of an array)
An Additional Detail in Java
Back SMYC Forward
  • Types of Exceptions:
    • Unchecked (Descendants of RuntimeException ) - Need not be caught or specified/re-thrown
    • Checked (Other descendants of Exception ) - Must be caught or specified/re-thrown
  • What This Means:
    • If you call a method that throws a checked exception you must either catch it or re-throw it
    • A method that throws a checked exception must have a throws clause in its declaration
Exceptions in UML
Back SMYC Forward
  • Visualization:
    • Include {exceptions=name[,...]} after the return type of the method to indicate that exceptions are thrown
  • An Observation:
    • You may or may not include the exception classes in the diagram (as needed)
There's Always More to Learn
Back -