# Exceptions Part I. Old Stuff To perform division one must first press a small button on the carriage which indicates where the decimal point should.

## Presentation on theme: "Exceptions Part I. Old Stuff To perform division one must first press a small button on the carriage which indicates where the decimal point should."— Presentation transcript:

Exceptions Part I

Old Stuff

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. From the manual:

142245 43500 4350 435 300 2020 7 327 142245/435 = ?

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 Basic ONERROR GOTO 100 C ch = getchar(); /* ch will be set equal to EOF on end of file */

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? 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 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( ) }

How would we use?…. Exceptions--Global Variables 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 }

continued 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:

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 } // doit Note: with this technique we potentially must wrap the ENTIRE program in a series of if/else clauses, duplicating code in places. (Do we prefer robustness or clarity/maintainability?) Exceptions--Global Variables Don’t write code like this!

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 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 Handling Exceptions thrown by someone else Throwing Exceptions & writing your own Exceptions Today Next Time

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 Handle in current method try { /* Code that might throw an exception */ } catch (ExceptionType ) { /* Code that handles exception */ } Handle outside current method void someMethod() throws Exception { } void someMethod throws AnotherException { } More details on this later! More details on this later!

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 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 Throwable ExceptionError AWTErrorThreadDeathIOExceptionRuntimeExceptionOutOfMemoryError

Details of the classes Object ErrorException RuntimeException Throwable others... getMessage printStackTrace toString IOException

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 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 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? 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. 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! 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 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 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! */ } Don’t pack up your books yet!

Scenario 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... readLine public String readLine() 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 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 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 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 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! Of course, if you use this technique you still need to deal with the problem!

Print an error message Log the exception Retry the method (maybe with default parameters) Restore the system to some previously known "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... OOA/OOD/OOP “Who” knows enough to handle the exception? local? high-level?

Questions?

Download ppt "Exceptions Part I. Old Stuff To perform division one must first press a small button on the carriage which indicates where the decimal point should."

Similar presentations