Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.

Similar presentations

Presentation on theme: "Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors."— Presentation transcript:

1 Exceptions: when things go wrong

2 Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors cause problems on compilation You’ve already declared i ; can’t declare it twice!

3 Logic errors: hard to catch public static double square(double x) { return 2 * x; } Program compiles just fine It appears to work It just doesn't do what you think it does.... But this doesn’t square it’s input: it multiplies it by two.

4 Runtime Errors Sometimes errors occur at runtime e.g. User inputs an empty string when content is expected e.g. A divisor turns out to be zero.... e.g. Array myArray of size X but program refers to myArray[X] (which doesn’t exist: X-1 is the last array index) e.g. A file your program tries to read from doesn’t exist Runtime Errors generate Exceptions

5 Runtime error code public class myError { public static void main(String[] args) { System.out.println(3/0); } This program will compile with no errors and will seem ok. However, this code will produce a runtime error (and hence an Exception ) when it runs, because you can’t divide a number by zero.

6 public static void main(String[] args) { try { System.out.println(3/0); } catch (Exception ex) { System.out.println("Error: " + ex.getMessage()); } } Surviving the crash......... This “trys” the statement that might go wrong (might produce an exception), and “catches” the Exception Object ex that is generated if something does go wrong. The exception object can then tell us (or the user) what the problem was.

7 A little terminology If we try to run some piece of code and something goes wrong at runtime, an exception is thrown If the exception is caught by a handler, the program lives on If it is not caught, the program dies a grisly death: it “crashes”.

8 ObjectThrowable Error Exception RunTimeException IOException Other Exceptions.. Exception is a pre-defined class. When we catch an exception, we can call methods that tell us about it e.g ex.getMessage()

9 RunTimeException ArithmeticException NullPointerException IndexOutOfBoundsException and others....... RunTimeExceptions: for shame!!!!!! These are considered to be your fault.......

10 RuntimeExceptions You do not have to catch RuntimeExceptions If your code is squeaky clean, these will never happen Requires defensive programming (e.g. checking every value entered by a user) Commercial-grade code requires an extremely defensive attitude

11 throwing an exception If some method you are writing might generate an exception, you can declare this in advance You delcare that your method “throws” and exception. Any other code using this method must do something about the exception: must catch that exception

12 Throwing an exception..... public void myMethod() throws Exception {.... do something dangerous! } Any code calling myMethod must use a try..catch block

13 Catching an Exception Class userError{ public static void main(String[] args){ try { myMethod(); } catch (Exception e) { System.out.println("Caught this: " + e); }

14 Suppose statement2 causes an exception: try { statement1; statement2; statement3; } catch (Exception e) {} statement4; Will statement1 be executed? YES: Statement2 is the problem will statement 3 be executed? NO: Statement2 causes an exception. At the exception execution jumps to the catch block will statement 4 be executed? YES lazyman's option!!!

15 Passing the buck public void m2() throws Exception { // do something dangerous } public void m1()throws Exception { // call m2 m2(); } Method M1 calls method M2. If M2 throws an exception to M1, M1 will throw that same exception onwards.

16 Exceptions come with Methods public String getMessage() public String toString() public void printStackTrace() –useful for debugging: where did the exception occur?

17 Catching different sorts of exception The Class Exception has various different subclasses (look them up in the API). We can catch different sorts of exceptions and do different things in response to them. try{ myArray[x] = myArray[x]/z; } catch(NullPointerException nullPointer){ System.out.println(“myArray[“+x+”] is empty”); } catch(IndexOutOfBoundsException outOfBounds){ System.out.println(“myArray[“+x+”] out of bounds”); } catch(ArithmeticException arithmetic){ System.out.println(“can’t divide by ”+z ); }

18 Finally........... If an exception occurs and is not caught, the method exits immediately If an exception does not occur, the complete code of the method is executed If an exception occurs and is caught, control passes to the handler, and then continues after the handler If a finally clause is provided, along with try and catch, that code is guaranteed to be executed, no matter what happens

19 try { statement1; statement2; } catch(Exception e) { statement3; } finally { statement4; } always if s1 does NOT cause an exception if either s1 or s2 causes an exception always

Download ppt "Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors."

Similar presentations

Ads by Google