exceptions

Post on 31-Dec-2015

37 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

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

ExceptionsExceptions

Part II

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

Two Main IdeasTwo Main Ideas

Handling Exceptions Thrown by Someone

Throwing Exceptions &Writing your own Exceptions

Last Time

Today

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

Details of the classesDetails of the classesObject

Error Exception

RuntimeException

Throwable

others...

getMessage

printStackTrace

toString

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.

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.

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!

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

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

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

// ...

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());

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);

}

}

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

// ...

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.

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!

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

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

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";

}

}

Lost Exceptions!Lost Exceptions!

public class LostMessage

{

void f() throws VeryImportantException

{

throw new VeryImportantException();

}

void dispose() throws HoHumException

{

throw new HoHumException();

}

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();

}

}

}

Lost Exceptions!Lost Exceptions!

The output is:

A trivial exception

at LostMessage.dispose(LostMessage.java:21)

at LostMessage.main(LostMessage.java:29)

• 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?

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!)

Questions?Questions?

top related