Presentation is loading. Please wait.

Presentation is loading. Please wait.

Intro to Exceptions (c) Eraj Basnayake

Similar presentations


Presentation on theme: "Intro to Exceptions (c) Eraj Basnayake"— Presentation transcript:

1 Intro to Exceptions (c) Eraj Basnayake
Introduction to Exceptions 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

2 Intro to Exceptions (c) Eraj Basnayake
Exceptions are run-time events which indicate an exceptional situation Int[] t = new int[10]; for(int i=0; i<100; i++) t[i] = … ArrayIndexOutOfBoundsException String s=null; System.out.println(s.length()); NullPointerException int i=5; for(int j=3;j>=-1;j--){ System.out.println(i/j); } ArithmeticException 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

3 Intro to Exceptions (c) Eraj Basnayake
Exception classes Object Throwable Error Exception RuntimeException Object Object Object Object Object Exceptions you have to catch (checked exceptions) Exceptions you do not need to catch (but can catch) 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

4 Intro to Exceptions (c) Eraj Basnayake
… methodC(…){ for(int j=3;j>=-1;j--){ System.out.println(i/j); } ArithmeticException … methodB(…){ methodC(…) } … methodA(…){ methodB(…) } Ignored code … main(…){ methodA(…) } 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

5 Intro to Exceptions (c) Eraj Basnayake
Exception Handling - I … methodC(…){ try{ for(int j=3;j>=-1;j--){ System.out.println(i/j); } }catch(ArithmeticException ae){ System.out.println(ae); ArithmeticException Ignored code … methodB(…){ methodC(…) } … methodA(…){ methodB(…) } … main(…){ methodA(…) } 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

6 Intro to Exceptions (c) Eraj Basnayake
Exception Handling - II … methodC(…) throws ArithmeticException{ for(int j=3;j>=-1;j--){ System.out.println(i/j); } … methodB(…) throws ArithmeticException{ methodC(…) } … methodA(…){ try{ methodB(…); catch(ArithmeticException ae){ System.out.println(ae); } Ignored code … main(…){ methodA(…) } 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

7 Intro to Exceptions (c) Eraj Basnayake
The try catch block try{ //code that may throw exception… }catch(ExceptionType1 e1){ //code to handle exceptions of type ExceptionType1 or subclass }catch(ExceptionType2 e2){ //code to handle exceptions of type ExceptionType2 or subclass … //more catch blocks if needed }finally{ //code always to be executed after try block code } Each try must have at least 1 catch A finally block (optional) is always executed regardless of what happens in the try 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

8 Intro to Exceptions (c) Eraj Basnayake
Structuring a method … doSoemthing(…){ // code that does not throw exceptions // try-catch-finally blocks //code that does not throw exceptions //try-catch-finally blocks } try{ //code that may throw exception… }catch(ExceptionType1 e1){ //code to handle exceptions }catch(ExceptionType2 e2){ … //more catch blocks if needed }finally{ //code always to be executed} 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

9 Intro to Exceptions (c) Eraj Basnayake
Example public class Foo{ public static int divide (int[] array, int index){ try{ System.out.println(“Try block”); array[index + 2] = array[index]/array[index+1]; System.out.println(“Done try”); }catch(ArithmeticException ae){ System.out.println(“Arithmetic exception”); }catch(ArrayIndexOutOfBoundsException aioobe){ System.out.println(“Index out of bounds”); }finally{ System.out.println(“finally”); } System.out.println(“Code outside of try”); public static void main(String[] args){ 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

10 Intro to Exceptions (c) Eraj Basnayake
Writing your own public class ZeroDivideException extends Exception{ private int index; public ZeroDivideException(){ index = -1;} public ZeroDivideException(int index){ super(“/ by zero”); this.index = index; } public int getIndex(){ return index; 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

11 this exception, fix it by setting array value to 1 and recalling
Throwing your own public static int divide (int[] array, int index) throws ZeroDivideException { try{ System.out.println(“Try block”); array[index + 2] = array[index]/array[index+1]; System.out.println(“Done try”); }catch(ArithmeticException ae){ System.out.println(“Arithmetic exception”); throw new ZeroDivideException(index+1); }catch(ArrayIndexOutOfBoundsException aioobe){ System.out.println(“Index out of bounds”); }finally{ System.out.println(“finally”); } System.out.println(“Code outside of try”); Write a main() to catch this exception, fix it by setting array value to 1 and recalling method for next index. 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

12 Exceptions: Why do we need it
ADVANTAGES: 1. Separating Error Handling Code from "Regular" Code Suppose you need to read an entire file in memory: readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } BUT: What happens if the file can't be opened? What happens if the length of the file can't be determined? What happens if enough memory can't be allocated? What happens if the read fails? What happens if the file can't be closed? 2/24/2019 From: java.sun.com

13 Exceptions: Why do we need it
One way to do it. errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } else { errorCode = -5; } return errorCode; “Spaghetti code”. Not good. 2/24/2019 From: java.sun.com

14 Exceptions: Why do we need it
BETTER WAY readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { } catch (memoryAllocationFailed) { } catch (readFailed) { } catch (fileCloseFailed) { } 2/24/2019 From: java.sun.com

15 Exceptions: Why do we need it
ADVANTAGES: 2: Propagating Errors Up the Call Stack method1 { try { call method2; } catch (exception) { doErrorProcessing; } method2 throws exception { call method3; method3 throws exception { call readFile; What’s good about that ? Only method 1 has to deal with errors. Only method1 decides what do if an error occurs. Consider the alternative: Each method will have to deal with errors. Do you always know ahead of time what to do with errors? 2/24/2019 From: java.sun.com

16 Exceptions: Why do we need it
ADVANTAGES: 3: Grouping Error Types, Error Differentiation. What’s good about that ? Gives you a lot of flexibility in error handling: you can either do it in a very general fashion, or in a very exact (error-specific) fashion. 2/24/2019 From: java.sun.com

17 Intro to Exceptions (c) Eraj Basnayake
Exception potpourri Accessing the message in the exception: getMessage() Accessing a stack trace: printStackTrace() public class String public String concat(String str) Concatenates the specified string to the end of this string. … Throws: NullPointerException - if str is null. 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

18 Intro to Exceptions (c) Eraj Basnayake
Exception Designing them in Method design - design by contract Assert pre-condition and throw exception if pre-condition is not met Try to reuse existing exceptions whenever possible If a line could throw an exception you can + catch and fix it within the method + throw it back to be dealt with by the caller. Javadoc: /** * method description/purpose/pre-condition <parameter list and description> <return value and description> <Exception1 if precondition1 is not met> <Exception2 if precondition2 is not met> * … */ … someMethod(…) throws Exception1, Exception2, … { } 2/24/2019 Intro to Exceptions (c) Eraj Basnayake


Download ppt "Intro to Exceptions (c) Eraj Basnayake"

Similar presentations


Ads by Google