Exceptions

26
Exceptions Exceptions Part II

description

Exceptions. Part II. What you need to know. Last time What happens when an exception is thrown What are your choices for handling exceptions The different kinds of exceptions Today How to write your own exceptions Details of the exception classes Why and when you should use exceptions - PowerPoint PPT Presentation

Transcript of Exceptions

Page 1: Exceptions

ExceptionsExceptions

Part II

Page 2: Exceptions

What you need to knowWhat you need to know

• Last time– What happens when an exception is thrown– What are your choices for handling exceptions– The different kinds of exceptions

• Today– How to write your own exceptions– Details of the exception classes– Why and when you should use exceptions– Some typical scenarios

Page 3: Exceptions

Two Main IdeasTwo Main Ideas

Handling Exceptions Thrown by Someone

Throwing Exceptions &Writing your own Exceptions

Last Time

Today

Page 4: Exceptions

The different kinds of exceptionsThe different kinds of exceptions

• Error– For the big guys

• Exception– The “standard” exception– Java enforces handling– An unusual condition

• RuntimeException– e.g. classCast Exception– Can indicate using a class improperly– No special handling

Page 5: Exceptions

Details of the classesDetails of the classesObject

Error Exception

RuntimeException

Throwable

others...

getMessage

printStackTrace

toString

Page 6: Exceptions

Why and when you should use Why and when you should use exceptionsexceptions

• If the method encounters a situation it can’t handle throw an exception

• Avoid using exceptions to indicate normal operations

• Use Design by Contract!– If a client calling a method has not fulfilled the contract throw a RuntimeException.

– If your method is unable to fulfill its contract, throw either an Exception or RuntimeException.

• If you are throwing an exception for an abnormal condition that you feel client programmers should consciously decide how to handle, throw an Exception.

Page 7: Exceptions

How to write your own exceptionsHow to write your own exceptions

• Make a subclass of– Exception

– Any existing exception

• Give it a name that represents what it is– class QueueEmptyException extends Exception

– Build in extra functionality (if desired)

• You might want to do this just to give it a name of your choosing• You might want to do this to add extra functionality like a static

counter.

Page 8: Exceptions

ScenariosScenarios• You are writing a collection class and you are wondering how to

handle the condition where the collection is empty but the bone-headed user* forgot to check.

• The demons running CENG217 have decided that you need to write your own exception or they’ll make you take the course over and over and over...

• You would like to see a fairly complex yet crystal clear example of exception usage

*Might be you if it’s late enough!

Page 9: Exceptions

You are writing a collection class and you are wondering You are writing a collection class and you are wondering how to handle the condition where the collection is how to handle the condition where the collection is empty but the bone-headed user forgot to check.empty but the bone-headed user forgot to check.

// class Queue (continued)

public Object dequeue() throws Exception

{

if(isEmpty())

throw new Exception

(“Should check isEmpty()

before dequeueing”);

else

// return the front object

// ... Note: We’re just throwing a plain old Exception

Page 10: Exceptions

The demons running CThe demons running CENG 217ENG 217 have decided that you have decided that you need to write your own exception or they’ll make you take need to write your own exception or they’ll make you take

the course over and over and over...the course over and over and over...

class QueueEmptyException extends Exception

{

public QueueEmptyException() {}

public QueueEmptyException(String message)

{

super(message);

}

}

This should go in its own file:QueueEmptyException.java

Page 11: Exceptions

Now we can use our own exceptionNow we can use our own exception

// class Queue (continued)

public Object dequeue() throws QueueEmptyException

{

if(isEmpty())

throw new QueueEmptyException

(“Should check isEmpty()

before dequeueing”);

else

// return the front object

// ...

Page 12: Exceptions

How do you use this queue?How do you use this queue?

do

{

try

{

element = myQueue.dequeue();

}

catch(QueueEmptyException qee)

{

System.out.println(“This can’t be happening!”);

System.out.println(qee.getMessage());

}

} while(! myQueue.isEmpty());

Page 13: Exceptions

Note: You could choose to make this a Note: You could choose to make this a RuntimeExceptionRuntimeException

class QueueEmptyException extends RuntimeException

{

public QueueEmptyException() {}

public QueueEmptyException(String message)

{

super(message);

}

}

Page 14: Exceptions

In which case...In which case...

// class Queue (continued)

public Object dequeue() throws QueueEmptyException

{

if(isEmpty())

throw new QueueEmptyException

(“Should check isEmpty()

before dequeueing”);

else

// return the front object

// ...

Page 15: Exceptions

How do you use this queue?How do you use this queue?

while(! myQueue.isEmpty())

{

element = myQueue.dequeue();

.

.

.

If an exception is thrown,the program will terminate.

If an exception is thrown,the program will terminate.

Page 16: Exceptions

You would like to see fairly complex yet crystal clear You would like to see fairly complex yet crystal clear examples of exception usageexamples of exception usage

public int getAge(int iSSN)

throws RecordKeepingException

{

int index = getHashKey(iSSN);

int iAge = myArray[index].getAge(iSSN);

if (iAge <= 0)

throw new RecordKeepingException

(“Exception: Age for “ + iSSN +

“ not in range: “ + iAge);

else

return iAge;

}

Home-grown!

Page 17: Exceptions

You would like to see fairly complex yet crystal clear You would like to see fairly complex yet crystal clear examples of exception usageexamples of exception usage

public TreeNode getNodeRecursively(int index, TreeNode currentNode) throws MissingNodeException

{if (currentNode == null)

throw new MissingNodeException(); // Node not found! else if (currentNode.getNumber() == index)

return currentNode;else if (currentNode.getNumber() > index)

return getNodeRecursively (index, currentNode.getLeftChild());

else return getNodeRecursively

(index, currentNode.getRightChild());} // getNodeRecursively

Page 18: Exceptions

You would like to see fairly complex yet crystal clear You would like to see fairly complex yet crystal clear examples of exception usageexamples of exception usage

public void initializeTreeNode(int iNumberNodes)

{

if (myTree == null)

throw new NullPointerException

(“Null tree found”);

/* NOTE: Runtime exception; no need to declare propagation */

else

for (int i=0; i < iNumberNodes; i++)

{

TreeNode newNode = new TreeNode( i );

myTree.insertNode(newNode);

}

} // initializeTreeNode

Page 19: Exceptions

Lost Exceptions!Lost Exceptions!

class VeryImportantException extends Exception

{

public String toString()

{

return "A very important exception!";

}

}

class HoHumException extends Exception

{

public String toString()

{

return "A trivial exception";

}

}

Page 20: Exceptions

Lost Exceptions!Lost Exceptions!

public class LostMessage

{

void f() throws VeryImportantException

{

throw new VeryImportantException();

}

void dispose() throws HoHumException

{

throw new HoHumException();

}

Page 21: Exceptions

Lost Exceptions!Lost Exceptions!

// Still in class LostMessage

public static void main(String[] args)

throws Exception

{

LostMessage lm = new LostMessage();

try

{

lm.f();

}

finally

{

lm.dispose();

}

}

}

Page 22: Exceptions

Lost Exceptions!Lost Exceptions!

The output is:

A trivial exception

at LostMessage.dispose(LostMessage.java:21)

at LostMessage.main(LostMessage.java:29)

Page 23: Exceptions

• Print an error message

• Log the exception

• Retry the method(maybe with default parameters)

• Restore the system to some previouslyknown "good" state.

• Set the system to some "safe" state.

•Let exception propagate to whoever called the method in which the exception arose

• Catch it and ignore it

“Catch it and ignore it” is generally bad: If the error was serious enough

to throw an exception, it should be dealt with, not ignored.

When Catching Exceptions you can . . .When Catching Exceptions you can . . .OOA/OOD/OOP“Who” knowsenough to handlethe exception?

local?

high-level?

Page 24: Exceptions

Be sure toBe sure to

• Not overuse exceptions– Don’t use to indicate normal operations

• Not underuse exceptions– Design by Contract– Don’t ignore

• Catch exceptions• Throw exceptions (Don’t have to!)• Write your own exceptions (Don’t have to!)

Page 25: Exceptions

Questions?Questions?

Page 26: Exceptions