Lecture slides

Download Report

Transcript Lecture slides

CSC 243 – Java Programming,
Spring, 2009
Tuesday, February 24,
start of week 7, Exceptions
Exception constructs already in use
• try {
• attempt to run a block of code
• } catch (Type_A_Exception taex) {
• Do something with taex, e.g., taex.getMessage()
• } catch (Type_A_Exception tbex) {
• Do something with tbex, e.g., print, then throw tbex
• } finally {
• Do this after all of the above, even after a return!
• }
Unchecked and checked exceptions
• javac forces client code to catch checked
exceptions
• unchecked exceptions need not be caught;
they can be
– java.lang.Error
• java.io.IOError – maybe a disk drive goes off line
– java.lang.RuntimeException
• java.lang.NullPointerException
• Other java.lang.Exceptions are checked
Throwing a new exception
• An explicit throw creates a new Exception.
– public int deleteTiles(String tileset) throws
ScrabbleException
• throw new ScrabbleException("Player " + name
•
+ " does not have " + tile.toString()
•
+ " to delete from set of tiles.");
Rethrowing an exception
• A rethrow catches and handles an Exception
object, then throws it again.
• } catch (NumberFormatException nx) {
•
System.err.println(“Exception: “
•
+ nx.getMessage();
•
nx.printStackTrace(); // to System.err
•
throw nx ; // This is the rethrow
An implicit throw
• An implicit throw allows a called method to
throw an Exception via the calling method.
– public String [][] move(String command) throws
ScrabbleException
• Invokes “int used =
players[nextPlayer].deleteTiles(validword);
• But move() does not catch deleteTiles’s exception:
– public int deleteTiles(String tileset) throws ScrabbleException
• The remove() implicitly throws deleteTile’s exception.
A Chained Exception
• A chained Exceptions tacks a detail message
onto an underlying cause Exception.
– } catch (NumberFormatException nx) {
–
throw new Exception(“detail message”, nx);
• Used to prepend a context-specific message to
an Exception thrown from a called method.
• The new Exception must have the appropriate
constructor. It may be a custom Exception.
Custom Exceptions
• A custom Exception inherits, directly or
indirectly, from java.lang.Exception.
– public class ScrabbleException extends Exception
• public ScrabbleException(String text)
– super(text); // Call to base class constructor.
• Client code can explicitly catch a custom
Exception.