Exceptions
This presentation is the property of its rightful owner.
Sponsored Links
1 / 26

Exceptions PowerPoint PPT Presentation


  • 133 Views
  • Uploaded on
  • Presentation posted in: General

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

Download Presentation

Exceptions

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Exceptions

Exceptions

Part II


What you need to know

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

    • Some typical scenarios


Two main ideas

Two Main Ideas

Last Time

Handling Exceptions

Thrown by Someone

Today

Throwing Exceptions &

Writing your own Exceptions


The different kinds of exceptions

The 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 classes

Details of the classes

Throwable

getMessage

printStackTrace

toString

others...

Object

Error

Exception

RuntimeException


Why and when you should use exceptions

Why and when you should use exceptions

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

How 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.


Scenarios

Scenarios

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


Exceptions

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.

// 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


Exceptions

The demons running CENG 217 have decided that you need to write your own exception or they’ll make you take 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 exception

Now 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 runtimeexception

Note: You could choose to make this a RuntimeException

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 queue1

How do you use this queue?

while(! myQueue.isEmpty())

{

element = myQueue.dequeue();

.

.

.

If an exception is thrown,

the program will terminate.


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

You would like to see fairly complex yet crystal clear examples 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 examples of exception usage1

You would like to see fairly complex yet crystal clear examples 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 examples of exception usage2

You would like to see fairly complex yet crystal clear examples 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 exceptions1

Lost Exceptions!

public class LostMessage

{

void f() throws VeryImportantException

{

throw new VeryImportantException();

}

void dispose() throws HoHumException

{

throw new HoHumException();

}


Lost exceptions2

Lost Exceptions!

// Still in classLostMessage

public static void main(String[] args)

throws Exception

{

LostMessage lm = new LostMessage();

try

{

lm.f();

}

finally

{

lm.dispose();

}

}

}


Lost exceptions3

Lost Exceptions!

The output is:

A trivial exception

at LostMessage.dispose(LostMessage.java:21)

at LostMessage.main(LostMessage.java:29)


Exceptions

local?

high-level?

When Catching Exceptions you can . . .

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

  • OOA/OOD/OOP

    “Who” knows

    enough to handle

    the exception?


    Be sure to

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


  • Login