Slides - SRU Computer Science

Download Report

Transcript Slides - SRU Computer Science

INTRODUCTION TO
EXCEPTIONS
• Exceptional Situations
• Syntax of Try, Catch, Throw
• Search Trees: Improving Search Speed
• Defining Your Own Exceptions
Exceptional Situations
• Exceptions model situations that do not
typically occur
– errors
– end of task
– failure to complete task
• Exceptions provide the programmer with
information regarding problems
– NullPointerExceptions print information via
System.err.println (to the shell)
– if unhandled, can terminate the program
• You can catch exceptions
– prevent program termination
– respond to exceptions usefully
– we’ll see how to do this in a few slides . . .
• Exceptions allow a method to delegate how
the exception is to be handled by a caller
• There is little reason to use exceptions in this
course
– they will become more useful in larger projects
– also extensively used for handling boundary
conditions
Exceptions
2 of 18
November 10, 2005
Exceptional Situations (Con’t)
• Exceptions can be thrown without causing Java to
crash
– Java terminates program only if error is fundamental to
functionality
– recall, ArrayIndexOutOfBoundsException and
NullPointerException usually don’t terminate
program but sometimes do, depending on location of the
error
– Java is permissive; will keep running if it can
• In other languages, (C, Pascal, etc.) program
either stops when an error occurs, or worse, keeps
going, often providing no information (C++ now
allows you to create your own exceptions)
Java is
Cooler!
Exceptions
3 of 18
November 10, 2005
Exceptions in Java
• Process for handling exceptions
–
–
–
–
try some code
catch exception thrown by tried code
finally, clean up if necessary
try, catch, and finally are reserved words
• try denotes code that may throw exception
– place questionable code within a try block
– a try block must be immediately followed by a
catch block. A catch block must be preceded by a
try block
• catch exception thrown in try block and
write special code to handle it
– catch blocks distinguished by type of exception
– can have several catch blocks, each specifying a
particular type of exception possibly thrown in try
block
– once exception is handled, execution continues
after the catch block in caller
• finally (optional)
– special block of code that is executed whether or
not exception is thrown
– follows catch block
Exceptions
4 of 18
November 10, 2005
Anatomy of Syntax
• try block enclosed in curly braces {}
• catch block mirrors method definition
– takes exception as formal parameter
• catch block based on type of exception
parameter it handles
– most specific exception type in an exception
hierarchy must lexically come first
– formal parameter of type
java.lang.Exception is the most general and
would catch any subclass from the exception
library
• Here’s the basic syntax (typically in sender):
try {
<code>
}
catch (most_specific_exception_type name) {
<code in response to exception>
}
catch (more_general_exception_type name) {
<code in response to exception>
}
...
finally { <code> }
Exceptions
5 of 18
November 10, 2005
Exception Call Stacks
• A method call within a try block may set off a
chain of method calls, the last of which
throws an exception
– Mike tells Sara to getADrink(); Sara tells Kate
to getADrink(); Kate tells Monica to
getADrink(). Monica is asleep and throws a
DrinkNotAvailableException
– may be several degrees of separation between
thrown exception and corresponding try/catch
blocks
• The call stack describes the location of an
Exception.
– For example, when you get a
NullPointerException:
– Java unwinds the call stack, checking at each step
to see if the method call is within a try block
– NullPointerException is uncaught - no try
block so terminates program (in some cases)
– usually, you wouldn’t want to catch a
NullPointerException because you wouldn’t
know how to handle it
– you use this stack trace to find out where the error
occurred so you can fix it!
Exceptions
6 of 18
November 10, 2005
Exception Call Stacks (Con’t)
• Exception resolution is like method resolution
– Start with the method that throws exception
– Work back up the chain of method calls until a try
/ catch block is found for that exception or a
superclass of that exception
• So, you do not necessarily have to try and catch
every exception at every level of calling
• But you’d better be sure that you catch the
exception at some point!
– An exception which is not caught by a a try /
catch block in your code will be caught by the
VM.
• All of your code is in fact within a general try /
catch block
try {
/* all of your code */
}
catch (java.lang.Exception e){
/* print call stack in shell */
}
– Mike should put getADrink() within a try block
and then write a catch block with parameter type
DrinkNotAvailableException
– In catch block can yell at Sara and ask Kate
instead.
• Note: can have nested try and catch
blocks within a catch block
Exceptions
7 of 18
November 10, 2005
Throwing Exceptions Explicitly
• Can define and throw exceptions yourself:
throw new DataOutOfBoundsException();
throw new QueueEmptyException()
• Useful for responding to special cases
– throw an exception for a different class to catch
– a method of error handling
– You should always catch your own exceptions!
• Every method that throws exceptions should
declare what exceptions it throws in method
declaration
public void myMethod() throws
DataOutOfBoundsException {
/* code */
throw new DataOutOfBoundsException();
}
• Method which calls myMethod() should
have a try block surrounding the method call
and a catch block which handles
DataOutOfBounds exception
Exceptions
8 of 18
November 10, 2005
An Exceptional Example
• In Queue, if dequeuing an empty queue,
let’s now tell the user of this (instead of
returning nothing)
– TailNode’s dequeue method throws exception
– Queue’s dequeue method catches exception
– You will have to write QueueEmptyException to
subclass off java.lang.RuntimeException
In class TailNode:
public Node dequeue(ObjectHolder result)
throws QueueEmptyException {
throw new QueueEmptyException();
}
In class Queue:
public Object dequeue() {
try {
ObjectHolder result =
new ObjectHolder();
_head.dequeue(result);
}
catch (QueueEmptyException e) {
//print message to screen that queue
//is empty.
}
return result.getObject();
//null if queue is empty
}
Exceptions
9 of 18
November 10, 2005
An Exceptional Example (con’t)
• Notice that HeadNode’s dequeue is
unchanged
In class HeadNode:
public Node dequeue(ObjectHolder result){
_next = _next.dequeue(result);
_next.setPrevious(this);
return this;
}
• Java simply searched up the method call
stack until it found that, in class Queue,
_head.dequeue(result); is contained in
a try block and therefore, should execute
that class’ catch block
• What is a QueueEmptyException?
– let’s learn how to create our own exception . . .
new StudentIncapacitatedException();
Exceptions
10 of 18
November 10, 2005
Defining Your Own Exceptions
• You can define your own specialized
exceptions
– inherit from generic RuntimeException class
– of course, you can also define methods for your
exception. How would you use these?
public class DataNotFoundException extends
java.lang.RuntimeException {
public DataNotFoundException(String dataName){
super(“Data value ” +
dataName +
“ not found.”);
}
}
• String passed to superclass constructor is
printed to output window along with stack
trace
• Error handling within exception class should
be general
– factor out code that you want executed whenever
such an exception is thrown
– catch block in caller can do additional, more
specific error handling particular to the situation
Exceptions
11 of 18
November 10, 2005
Exception Hierarchies
• Exceptions are Java classes
– typically just include string describing error
– but can attach arbitrary state to exception; may
help caller handle exception
• Java already defines many standard
exceptions
– math exceptions
– system exceptions
– input/output exceptions
Throwable
Exception
RuntimeException
IOException
Your Exception Here
NullPointerException
Exceptions
12 of 18
November 10, 2005
QueueEmptyException
• So, create your own
QueueEmptyException:
– subclass of java.lang.RuntimeException
– although class doesn’t really do anything in this
case, it is needed to specify the type of runtime
exception which will be handled by a caller
– if we didn’t throw our own specialized exception
but instead threw a pre-existing exception such as
NullPointerException, we would
misrepresent the error, and catch block might
mistakenly intercept other (real)
NullPointerExceptions
public class QueueEmptyException extends
java.lang.RuntimeException{
public QueueEmptyException() {
super();
}
}
• Remember, exceptions should only be thrown
in special cases and the type should be as
specific as possible
Exceptions
13 of 18
November 10, 2005
Another Example: Deletion in Linear List
• When method detects abnormal
condition, throw exception that can be
caught by calling method
• Only delete methods change:
public class InternalNode<ElementType extends
Comparable<ElementType>> extends
Node<ElementType> {
// code elided
public Node<ElementType> delete(ElementType
keyToDelete)
throws DataNotFoundException {
Node<ElementType> nodeToReturn = this;
if (_data.compareTo(keyToDelete) == 0) {
nodeToReturn = _next;
}
else if (_data.compareTo(keyToDelete) < 0){
_next = _next.delete(keyToDelete,
result);
}
else{
throw new DataNotFoundException(
keyToDelete.toString());
}
return nodeToReturn;
}
}
• User of list must catch exception
Exceptions
14 of 18
November 10, 2005
A Game of Catch:
public class ListUser{
private List<CSStudent> _list;
// code elided
public void delete(CSStudent data){
try {
_list.delete(data);
}
catch (DataNotFoundException notFound){
// code to handle exception elided
}
}
}
• User’s delete tries to delete value not in list
– Call to delete is recursively propagated through list
to an internal node that sees that the data can’t be
in the list
– Internal node’s method throws
DataNotFoundException which is caught and
handled by ListUser
Exceptions
15 of 18
November 10, 2005
Exceptions: Pros and Cons
• Using Exceptions is a design choice
• Traditional ways to handle errors
–
–
–
–
return special error value (C/C++)
set global error flag (C)
call special method (C++)
terminate program (SkyNet)
• Exceptions help solve these problems when
handling errors because:
– one class can detect error, other can fix it
– throwing specific exceptions helps debugging
– better use of encapsulation
Exceptions
16 of 18
November 10, 2005
Exceptions: Pros and Cons
(continued)
• Pros:
– cleaner code: rather than return a boolean up the
chain of calls to check for exceptional case, throw
exception
– lets you use return value for something meaningful
beyond error checking
– error handling not mixed in with normal code
• Cons:
– throwing exceptions requires a lot of computation
– can become messy if not used sparingly
– be careful not to catch exceptions such as
NullPointerExceptions which might be better
left uncaught
• Words of Wisdom:
– typically place try blocks high up in the program to
maximize scope
– shouldn’t model a standard part of program with
exceptions
– use to handle special cases which are beyond the
regular operation of the program
– throw an exception when an error occurs which
you can’t deal with and which is better handled by
a class higher up in the stack trace
Exceptions
17 of 18
November 10, 2005
Exceptions
18 of 18
November 10, 2005