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

Exceptions PowerPoint PPT Presentation


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

Exceptions. Part I. Old Stuff. From the manual:. To perform division one must first press a small button on the carriage which indicates where the decimal point should be situated in the quotient (bölüm) .

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 I


Old stuff

Old Stuff


Exceptions

From the manual:

  • To perform division one must first press a small button on the carriage which indicates where the decimal point should be situated in the quotient(bölüm).

  • Then, the dividend(bölünen) is entered on the big keyboard, and the "ENTER DIVD" button is pressed. This shifts the carriage over to the position indicated for the decimal point, and enters the dividend into the accumulator.

  • Then, the keyboard is cleared (if the "ADD" key is on, the keyboard clears automatically, however, if it is off, the keyboard must be cleared manually with the "K B CLEAR" key), and the divisor(bölen) entered into the big keyboard.

  • Then, BOTH divide keys are depressed simultaneously, and the machine begins a process of shifting the carriage to the right to find a point where the divisor can start to be subtracted from the dividend.

  • Once that point is found, then successive subtractions of the divisor occur until an overdraft (IE: the accumulator goes negative) occurs, and each subtraction is counted in the counter register.

  • A single addition of the divisor corrects for the overdraft, and then the carriage shifts to the left, and the process repeats until the quotient is left in the counter register, and the remainder is left in the accumulator.


Exceptions

142245

43500

43500

43500

4350

4350

435

435

435

435

435

435

435

300

20

7

327

142245/435 = ?


Slight problem

Slight problem

  • If division by zero is attempted the calculator just keeps trying to subtract and never stops. Very exciting!

  • Okay for a machine with an operator but what about an automatic machine?

  • Need to take action upon encountering certain error conditions like “division by zero”

  • Architecture modified to detect error conditions and branch to handler code.

  • So how do we handle the situation?


Early approaches to errors

Early Approaches to Errors

  • Basic

    ONERROR GOTO 100

  • C

    ch = getchar();

    /* ch will be set equal to EOF on end of file */


Basic problems

Basic Problems

  • Programmers never think they will make errors

  • Programmers are wrong a lot!

  • Want to make code robust(sağlam)

  • Want to force users to maintain robustness

  • Need a “clean” way of handling problems


Solutions

Solutions?

  • Could have methods return a value that tells us whether or not we had an error?

    • Then can’t return anything else or

    • Have to return a composite object

  • Even with some kind of error code

    • Does it give us enough information?

    • Does it give us flexibility

    • Does it include a way to make sure we check it?


Exceptions traditional methods

Exceptions--Traditional Methods

if (someMethod( ) == true) {

if (someOtherMethod( ) == true) {

if (someThirdMethod( ) == true) {

// no errors; do intended actions

}

else {

// handle error caused by someThirdMethod( )

}

}

else {

// handle some error caused by someOtherMethod( )

}

}

else {

// handle some error caused by someMethod( )

}


Exceptions global variables

Exceptions--Global Variables

How would we use?….

  • Another way to deal with error handling is to have the value of a global variable represent the error.

    int iErrorValue = 0;

    public void someMethod( ) {

    // do someMethod’s stuff here

    // if there is an error, then set iErrorValue = 1

    }

    public void someOtherMethod( ) {

    // do someOtherMethod’s stuff here

    // if there is an error, then set iErrorValue = 2

    }

    public void someThirdMethod( ) {

    // do someThirdMethod’s stuff here

    // if there is an error, then set iErrorValue = 3

    }


Exceptions global variables1

Exceptions--Global Variables

public void doIt()

{

someMethod();

someOtherMethod();

someLastMethod();

if (iErrorValue == 1)

...

if (iErrorValue == 2)

...

if (iErrorValue == 3)

...

}

But: What if the run-time error stopped us from continuing?

For example: What if someMethod( ) failed in such a way that we cannot go on to someOtherMethod( )?

To cope, we find ourselves with code that’s nearly as messy as the earlier example which featured multiple nested-ifs:

continued


Exceptions global variables2

Exceptions--Global Variables

Note: with this technique

we potentially must wrap

the ENTIRE program

in a series of if/else clauses,

duplicating code in places.

public void doit( ) {

someMethod( );

if (iErrorValue == 1)

/* Handle Error 1 here */

else {

someOtherMethod( );

if (iErrorValue == 2)

/* handle Error 2 here */

else {

someThirdMethod( );

if (iErrorValue == 3)

/* Handle Error 3 here */

else {

/* do intended actions here */

} // else

} // else

} // else

} // doit

(Do we prefer robustness

or clarity/maintainability?)

Don’t write code like this!


Solution

Solution

  • Exceptions

  • Java uses termination model of exception handling:program control cannot return directly to the throw point

    • resumption model of exception handling: control would return to thepoint at which the exception occurred and resume execution.

  • Exceptions are thrown

    • like an NFL referee throws a penalty flag

  • Exceptions can be thrown by Java (Today)

  • Exceptions can be thrown by you! (Next Time)


What you need to know

What you need to know

  • Today

    • What happens when an exception is thrown

    • What are your choices for handling exceptions

    • The different kinds of exceptions

  • Next Time

    • How to write your own exceptions

    • Details of the classes

    • Why and when you should use exceptions

    • Some typical scenarios


Two main ideas

Two Main Ideas

Today

Handling Exceptions

thrown by someone else

Next Time

Throwing Exceptions &

writing your own Exceptions


What happens when an exception is thrown

What happens when an exception is thrown?

  • An exception object is created (on the heap)

  • The current “context” is halted/aborted

  • Execution starts in some error handling code

    • Can be in current method

    • Can be external to current method

  • The error handling code has access to the exception object which can be used to

    • Access a String message contained in the exception

    • Determine what type of exception was thrown

    • Print a stack trace

    • Other cool stuff (like rethrow the exception, increment a counter, etc.)


What are your choices for handling exceptions

What are your choices for handling exceptions

  • Handle in current method

    try

    {

    /* Code that might throw an exception */

    }

    catch (ExceptionType <ident>)

    {

    /* Code that handles exception */

    }

  • Handle outside current method

    void someMethod() throws Exception { }

    void someMethod throws AnotherException { }

More details

on this later!


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


15 4 java exception hierarchy

15.4 Java Exception Hierarchy

  • Superclass Throwable

    • Subclass Exception

      • Exceptional situations

      • Should be caught by program

    • Subclass Error

      • Typically not caught by program

  • Checked exceptions

    • Catch or declare

  • Unchecked exceptions


Inheritance hierarchy for class throwable

Inheritance hierarchy for class Throwable

AWTError

ThreadDeath

IOException

RuntimeException

OutOfMemoryError

Throwable

Exception

Error


Details of the classes

Details of the classes

Throwable

getMessage

printStackTrace

toString

others...

Object

Error

Exception

IOException

RuntimeException


15 8 printstacktrace getstacktrace and getmessage

15.8 printStackTrace, getStackTrace and getMessage

  • Throwable class

    • Method printStackTrace

      • Prints method call stack

    • Method getStackTrace

      • Obtains stack-trace information

    • Method getMessage

      • Returns descriptive string


Nitty gritty

Nitty Gritty

  • A method which throws an exception must explicitly “announce” this fact (compiler enforced) in the method header throw clause

    public void someMethod() throws SomeException

    UNLESS

  • The exception is a RuntimeException (or a child of RuntimeException)

    OR

  • The exception is handled inside the method


Here s the idea

Here’s the idea

  • If you as a developer write a class with a method that throws an exception then Java forces all users of the class to deal with it.

  • This is unlike earlier programming languages where there was no way to insure that programmers properly handled error conditions.

  • Again we try to deal with problems at compile time as opposed to runtime


But what about runtimeexceptions

But what about RuntimeExceptions?

  • Certain types of exceptions can occur in almost every method and including code for these conditions would be burdensome

  • Runtime Exception Examples:

    • ArithmeticException

    • ClassCastException

    • EmptyStackException

    • IllegalArgumentException

    • IndexOutOfBoundsException

    • UnsupportedOperationException

    • NegativeArraySizeException

    • NoSuchElementException

    • NullPointerException

So no special note

must be made in

method headers.

And it doesn’t have to be handled. Program can be allowed to terminate.


Handle them yourself

Handle Them Yourself!

  • One or more statements that might throw an exception are placed in a try block

  • The try block is followed by one or more catch blocks

    catch(IOException ioe)

    {

    /* Code to handle IOException here e.g.:*/

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

    }

    catch(Exception e)

    {

    /* Code to handle other exceptions here */

    }

Put the subclasses before the classes


15 6 finally clause

15.6 finally Clause

  • Resource leak

    • Caused when resources are not released by a program

  • The finally block

    • Appears after catch blocks

    • Always executes

    • Use to release resources


Finally

Finally

Don’t pack up

your books yet!

  • In certain cases (no matter what) it is desirable to have some code that will be executed after the try block. (Like closing a file or a network connection).

  • This means whether or not exceptions were encountered.

  • The solution is the finally block

    try {}

    catch(Ex1 e) {}

    catch(Ex2 e) {}

    finally

    {

    /* Code that will execute! */

    }


Scenario

Scenario

  • You are trying to use a method that throws an exception. The compiler is complaining. It’s late.


You are trying to use a method that throws an exception the compiler is complaining it s late

You are trying to use a method that throws an exception. The compiler is complaining. It’s late.

class SomeClass {

...

public void someMethod(...) {

...

BufferedReader stdin = new BufferedReader(

new InputStreamReader(System.in));

inbuf = stdin.readLine();

...

}

...

}

C:>javac SomeClass.java

SomeClass:299: Exception java.io.IOException must be caught, or it must be declared in the throws clause of this method.

inbuf = stdin.readLine();

^

1 error


Check the api

Check the API...

readLine

public StringreadLine()

throws IOException

Read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Returns:

A String containing the contents of the line, not including any line-

termination characters, or null if the end of the stream has been reached

Throws:

IOException - If an I/O error occurs


You are trying to use a method that throws an exception the compiler is complaining it s late1

You are trying to use a method that throws an exception. The compiler is complaining. It’s late.

BufferedReader stdin = new BufferedReader(

new InputStreamReader(System.in));

try

{

inbuf = stdin.readLine();

}

catch (IOException ioe)

{

System.out.println("Oh, darn!");

}

Java requires you to somehow handle the

exception. It doesn’t require you to do

anything smart.


You are trying to use a method that throws an exception the compiler is complaining it s late2

You are trying to use a method that throws an exception. The compiler is complaining. It’s late.

class SomeClass {

...

public void someMethod(...) throws IOException {

...

BufferedReader stdin = new BufferedReader(

new InputStreamReader(System.in));

inbuf = stdin.readLine();

...

}

...

}

Or you could just add

throws IOException

to the method header


You are trying to use a method that throws an exception the compiler is complaining it s late3

You are trying to use a method that throws an exception. The compiler is complaining. It’s late.

class SomeClass {

...

public void someMethod(...) throws IOException {

...

BufferedReader stdin = new BufferedReader(

new InputStreamReader(System.in));

inbuf = stdin.readLine();

...

}

...

// Someplace else

someReference.someMethod() // Now this line is a problem!!!

}

Of course, if you use this

technique you still need

to deal with the problem!


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?


    Questions

    Questions?


  • Login