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

Things that can go wrong

Embed Size (px)

DESCRIPTION

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 - PowerPoint PPT Presentation

Citation preview

Page 1: Things that can go wrong

Things that can go wrong

• Logic error – The program is incorrect

• Environment error - e.g. out of memory

• I/O error – e.g., lost network connection.

04/20/23 1ITK 275

What do we do?

Page 2: Things that can go wrong

Exceptions

• Throwing Exceptions 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)

In Java, they are classes

04/20/23 2ITK 275

Page 3: Things that can go wrong

Exception throwing

The sequence of calling

The sequence of throwingexceptions

X

bad thing happens

JVM starts application at main()

main() calls method a()

method a method b()

method b method c()

method c exception occurs

If the exception cannot be handled here, it will continue to throw back

04/20/23 3ITK 275

Page 4: Things that can go wrong

Generating an ArithmeticException

8 /** 9 * Compute quotient of numerator / denominator. 10 * Assumes denominator 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

04/20/23 4ITK 275

Page 5: Things that can go wrong

Categories of exceptions

• 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 categorization affect compile-time behavior only

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.

04/20/23 5ITK 275

Page 6: Things that can go wrong

Unchecked Exceptions handle:

• Logic error – The program is incorrect

• Environment error - e.g. out of memory

• I/O error – e.g., lost network connection.

04/20/23 6ITK 275

Checked Exceptions handle:

Page 7: Things that can go wrong

Java’s Exception Hierarchy

Unchecked

Checked

Page. 112

Page 8: Things that can go wrong

Example of handling a checked exception

public static int 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;}

04/20/23 8ITK 275

Page 9: Things that can go wrong

Try-Catch-Finally Blockstry { 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}

Page 10: Things that can go wrong

Example of Try-Catch-Finally Blocksint[] a = new int[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***");}

Error:java.lang.ArithmeticException: / by zeroSum is 0All is cool***

quotient is 1.0Sum is 1All is cool***

quotient is 0.0Sum is 3All is cool***

The array is too small!Sum is 3All is cool***

The array is too small!Sum is 3All is cool***

04/20/23 10ITK 275

Throwing runtime/uncheck exceptions is controversial

Page 11: Things that can go wrong

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!

04/20/23 11ITK 275

Page 12: Things that can go wrong

Throwing 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.

Document that the method throws an exception

04/20/23 12ITK 275

Page 13: Things that can go wrong

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

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!!"); } }}

04/20/23 13ITK 275

Page 14: Things that can go wrong

04/20/23 14ITK 275

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

Page 15: Things that can go wrong

Custom Exception Classes

package gray.adts.shapes; /** * The exception 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 ); }}

Create a custom unchecked exception classsimply by extending RuntimeExceptionand providing two constructors. Everythingelse you need is inherited from Throwable!

extends

Exception

for unchecked

04/20/23 15ITK 275