1 / 15

Things that can go wrong

Things that can go wrong. What do we do?. Logic error – The program is incorrect  Environment error - e.g. out of memory I/O error – e.g., lost network connection. Exceptions. In Java, they are classes. Throwing Exceptions is Java’s way of telling you something has gone wrong

dawn-bush
Download Presentation

Things that can go wrong

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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Things that can go wrong What do we do? • Logic error – The program is incorrect  • Environment error - e.g. out of memory • I/O error – e.g., lost network connection. ITK 275

  2. Exceptions In Java, they are classes • ThrowingExceptions is Java’s way of telling you something has gone wrong • When an “exceptional condition” occurs, an exception object is created storing information about the nature of the exception (kind, where it occurred, etc.). When this happens, we say that “an exception is thrown”. • The JVM looks for a block of code to catch and handle the exception (do something with it) ITK 275

  3. Exception throwing bad thing happens The sequence of throwing exceptions method c  exception occurs X If the exception cannot be handled here, it will continue to throw back method b  method c() method a  method b() main() calls  method a() JVM starts application at main() The sequence of calling ITK 275

  4. Generating an ArithmeticException 8 /** 9 * Compute quotient of numerator / denominator. 10 * Assumesdenominator is not 0. 11 */ 12 public static int computeQuotient(int numerator, 13 int denominator) { 14 return numerator / denominator; 15 } Enter two integers: 8 0 Exception in thread “main” java.lang.ArithmeticException: / by zero at ExceptionEx.computeQuotient(ExceptionEx.java:14) at ExceptionEx.main(ExceptionEx.java:27) stack trace ITK 275

  5. Categories of exceptions These categorization affect compile-time behavior only • Checked exceptions – descended from class Exception, but outside the hierarchy rooted at RuntimeException. The compiler will check that you either catch or re-throw checked exceptions. • Unchecked exceptions – (aka Runtime Exception ) represent the kinds of errors your program can avoid through careful programming and testing. The compile does not check to see that you handle these exceptions. These represent some error, not programmer’s fault, but the programmer can (should) do something about it They are programmer’s fault, the compiler can’t do a thing. ITK 275

  6. Unchecked Exceptions handle: • Logic error – The program is incorrect  • Environment error - e.g. out of memory • I/O error – e.g., lost network connection. Checked Exceptions handle: ITK 275

  7. Java’s Exception Hierarchy Page. 112 Unchecked Checked

  8. Example of handling a checked exception publicstaticint countCharsInAFile(String str) { Scanner in =null; int wordNo = 0; try { File file = new File(str); in = new Scanner(file); } catch(FileNotFoundException ex) { System.out.println(ex.getMessage()); System.exit(1); } while (in.hasNextLine()) { String aLine = in.nextLine(); wordNo += aLine.length(); } in.close(); return wordNo; } ITK 275

  9. Try-Catch-Finally Blocks try { program statements; some of which may throw an exception } catch ( ExceptionType1 exception ) { program statements to handle exceptions of type ExceptionType1 or any of its subclasses } catch ( ExceptionType2 exception ) { program statements to handle exceptions of type ExceptionType2 or any of its subclasses } … . . . other catch clauses … catch ( ExceptionTypeN exception ) { program statements to handle exceptions of type ExceptionTypeN or any of its subclasses } finally { this block is optional; this block will execute whether or not an exception is thrown }

  10. Example of Try-Catch-Finally Blocks • int[] a = newint[3]; • int sum = 0; • double q=0; • a[0]=0;a[1]=1;a[2]=2; • for (int i=0;i<5;i++) • try { • sum += a[i]; • q = a[i]/sum; • System.out.println("\nquotient is "+q); • } • catch (IndexOutOfBoundsException ioobe) • { • System.out.println("\nThe array is too small!"); • } • catch (ArithmeticException e) • { • System.err.printf("\nError:%s\n",e); • } • finally { • System.out.println("Sum is "+sum); • System.out.println("All is cool\n***"); • } Throwing runtime/uncheck exceptions is controversial Error:java.lang.ArithmeticException: / by zero Sum is 0 All is cool *** quotient is 1.0 Sum is 1 All is cool *** quotient is 0.0 Sum is 3 All is cool *** The array is too small! Sum is 3 All is cool *** The array is too small! Sum is 3 All is cool *** ITK 275

  11. The programmer can throw Exceptions e.g., to complain about method’s pre-conditions that are not met • Example: • // expects its argument to be greater than 0. • setLength( double theLength ) • What to do when that precondition isn’t met? •  throw an exception! ITK 275

  12. Throwing an Exception Document that the method throws an exception /** * Set the length dimension of this <tt>Rectangle</tt>. * @param theLength the new length of this <tt>Rectangle</tt>; * must be > 0 * @throws IllegalArgumentException if <tt>theLength</tt> is <= 0. */ public void setLength( double theLength ) { if ( theLength <= 0 ) throw new IllegalArgumentException(“Illegal Rectangle length (“ + theLength + ”): must be > 0 “); this.length = theLength; } Create an exception object the way you create any other kind of object, with new. Throw the exception with the reserved word throw. ITK 275

  13. catch (NumberFormatException ex) { • System.out.println("\n"+ex.toString()); • ex.printStackTrace(); • } • catch (IllegalArgumentException ex) { • System.out.println("\n"+ex.toString()); • ex.printStackTrace(); • } • catch (ArrayIndexOutOfBoundsException ex) { • System.out.println("\n"+ex.toString()); • ex.printStackTrace(); • } • catch (IndexOutOfBoundsException ex) { • System.out.println("\n"+ex.toString()); • ex.printStackTrace(); • } • catch (RuntimeException ex) { • System.out.println("\n"+ex.toString()); • ex.printStackTrace(); • } • finally { • System.out.println("\nWe are done. Finally!!"); • } • } • } public class HandleExceptions { public static void main(String[] args) { System.out.println("Testing Exception Handling\n"); try { int i=1,j=2; Exception myEx=null; String s="0.2"; i=Integer.parseInt(s); if (i > j) throw new RuntimeException(); int[] A = new int[5]; i=1; if (i<2 || i>4) throw new IndexOutOfBoundsException(); i = 5; i = A[i]; } catch (ArithmeticException ex) { System.out.println("\n"+ex.toString()); ex.printStackTrace(); catch (NullPointerException ex) { System.out.println("I'm here 12345"); System.out.println("\n"+ex.toString()); ex.printStackTrace(); } ITK 275

  14. A well designed method should throw appropriate exceptions. (API) ITK 275

  15. Custom Exception Classes Create a custom unchecked exception class simply by extending RuntimeException and providing two constructors. Everything else you need is inherited from Throwable! package gray.adts.shapes; /** * Theexception that is thrown whenever an operation on a * shape is in violation of a method pre-condition. */ public class ShapeException extends RuntimeException { public ShapeException() { super(); } public ShapeException( String errMsg ) { super(“ “ + errMsg ); } } extends Exception for unchecked ITK 275

More Related