1 Syntax errors Logic errors Three Example Exceptions

143 downloads 176 Views 775KB Size Report
A syntax error is a violation of the notational rules of the programming language. ( synonym: compile-time errors). Programming errors (faults) occur in two basic ...
Programming errors (faults) occur in two basic forms:

Syntax errors ! !A syntax error is a violation of the notational rules of! !the programming language. (synonym: compile-time errors)

Logic errors ! !A logic error results in potentially faulty behavior. ! !Some logic errors are detected by the Java VM. !

The Object of Data Abstraction and Structure, David D. Riley

© Addison Wesley pub.



A detected error is generally called a run-time error. ! Java run-time errors produce exceptions. ! An exception is an abnormal condition that occurs during software execution. !

Three Example Exceptions

String str = null; str = str.toLowerCase(); int j = 0; int k = 25/j; double[ ] arr = new double[3]; arr[3] = 29.4;

When an exception occurs, it is said that “the exception is ”___________”.! The Object of Data Abstraction and Structure, David D. Riley

© Addison Wesley pub.



1

Exception reports

driley> java Driver! Exception in thread "main" java.lang.NullPointerException! at Driver.main(Driver.java:5)! driley>

String str = null; str = str.toLowerCase();

driley> java Driver!

int j = 0; int k = 25 / j;

Exception in thread "main" java.lang.ArithmeticException: / by zero! at Driver.main(Driver.java:8)

driley> !

double[ ] arr = new double[3]; arr[3] = 29.4; driley> java Driver! Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException! at Driver.main(Driver.java:11)

driley> !

The Exception message includes the following information:! !• name of the method executing when the exception is thrown.! • type of exception that occurred.! • traceback of all active methods (and class(es), line number(s)).!

Exception traceback

driley> java Driver!

Exception occurs in ! !line ! !of method! !in class!

Exception in thread "main" java.lang.NullPointerException! at Thing.doSomething(Thing.java:9)! at Thing.(Thing.java:5)! at Driver2.main(Driver2.java:3)

doSomething called from ! driley> !

!line !

The Object of Data Abstraction and Structure, David D. Riley

© Addison Wesley pub.



of ! constructor !

Thing constructor called from ! !line of ! ! method of ! ! class. !

2

It is also possible to simulate an exception by executing a throw instruction.! throw ExceptionObject; ! where ExceptionObject is an object reference conforming to Exception (Exception is a class from java.lang.) ! public class SimpleFraction {

Example

private int numerator, denominator;

public class runFractTest {

public SimpleFraction(int n, int d) { IllegalArgumentException error; if (d != 0) { numerator = n; denominator = d; } else { error = new IllegalArgumentException( “Fraction denominator of 0”); throw error; } } public double realValue() { return numerator / denominator; } ... The Object of Data Abstraction

public static void main(String[ ] args) { SimpleFraction myFrac; myFrac = new SimpleFraction(1, 2); System.out.println(myFrac.realValue()); myFrac = new SimpleFraction(1, 0); System.out.println(myFrac.realValue()); }

}

}



and Structure, David D. Riley

© Addison Wesley pub.

program executing normally exception is thrown

program is interrupted exception handler executes

program terminates

??? The Object of Data Abstraction and Structure, David D. Riley

© Addison Wesley pub.



3

try Syntax

try

{!

tryInstructionBody! } catchClauses! finallyClause !

catchClauses Syntax (zero or more repetitions of the following)

catch

(exceptionClassName parmName ) {!

exceptionHandlerBody! }!

finallyClause Syntax (optional)

finally {! finallyBody! }! The Object of Data Abstraction and Structure, David D. Riley

© Addison Wesley pub.



...Body denotes a sequence of instructions.! exceptionClassName - class conforming to Throwable.! parmName - serves as a parameter passed into catch.!

try Semantics

• Execution of the try begins by ! executing the tryInstructionBody.!

Trace the following:!

System.out.println( “La Crosse” ); try { • During the execution of tryInstructionBody ! System.out.println( “River Falls” ); String str; the catchClauses serve as exception handlers.! The appropriate catchClause is selected by ! System.out.println( str.trim() ); System.out.println( “Eau Claire” ); conformance to a catchClauseName ! } catch ( NullPointerException e) { System.out.println( “Platteville” ); • If a finallyClause is included, then! } it always executes after the try.! catch ( ArithmeticException e) { System.out.println( “Oshkosh” ); } finally { System.out.println( “Whitewater” ); }

What if this line is deleted?! The Object of Data Abstraction and Structure, David D. Riley

© Addison Wesley pub.



4

Details of Exception Handling Behavior

When an exception is thrown execution proceeds as follows:! 1)Normal instruction execution is suspended.! 2)If the immediately enclosing try contains a matching catch, then the ! conforming catch clause serves as the exception handler. ! Otherwise, the current try body is aborted and the thrown exception! is forwarded to the next instruction after the try. (If this is the last ! instruction in a method, then the exception is forwarded to the ! location of the call.)! 3)Repeat Step 2 until an exception handler is located or all try instructions! are exhausted.! 4)The exception handler is executed, followed by finallyClause (if present).! The remainder of the try instruction containing the catchClause is aborted! and execution proceeds with the next instruction after the try.! 5)If no matching catchClause is found, then this is considered to be an! uncaught exception and the program terminates with a traceback.! The Object of Data Abstraction and Structure, David D. Riley

© Addison Wesley pub.



Example

Start trace by executing cud.

public void cud() { try { System.out.println( "cud: before horn" ); horn(); System.out.println( "cud: after horn" ); udder(); System.out.println( "cud: after udder" ); } catch ( Exception e ) { System.out.println( "cud handler" ); } } public void horn() { try { System.out.println( "horn: before udder" ); udder(); System.out.println( "horn: after udder" ); } catch ( Exception e ) { System.out.println( "horn handler" ); } }

The Object of Data Abstraction and Structure, David D. Riley

© Addison Wesley pub.



public void udder() { System.out.println( ”udder: before exception" ); throw( new ArithmeticException() ); System.out.println( ”udder: after exception" ); }

5

All Java exceptions are represented by objects. (These objects are automatically passed as parameters to the exception handler.)

Throwable

The superclass of all exception objects is _________________.

«constructor»! + Throwable()! . . .!

Exceptions partitioned into two categories. !

Unchecked Exceptions !

«other»! + String getMessage()! + void printStackTrace()! + String toString()! . . .!

!• are often severe, unpredictable.! !• may (or may not) be handled by a try instruction. !

Checked Exceptions ! !• should be used for user-created exceptions.! !• must either be handled by a catch or included in a ! ! throws declaration. (throws explained later.) ! The Object of Data Abstraction and Structure, David D. Riley

© Addison Wesley pub.



Classes from java.lang.

Error subclasses (abridged) !

Object!

!OutOfMemoryError! !StackOverflowError !

Throwable!

Exception subclasses (abridged) ! Error!

!IOException !

Exception!

RuntimeException (abridged) ! Unchecked

RuntimeException! Checked Unchecked

!ArithmeticException ClassCastException IllegalArgumentException IndexOutOfBoundsException NegativeArraySizeException NullPointerException SecurityException ! The Object of Data Abstraction and Structure, David D. Riley

© Addison Wesley pub.



6

Example

try { ... } catch ( NullPointerException e ) { System.out.println( ”null handler" ); } catch ( IndexOutOfBoundsException e ) { System.out.println( ”index handler" ); } catch ( OutOfMemoryError e ) { System.out.println( ”memory handler" ); } catch (Exception e ) { System.out.println( e ); }

The Object of Data Abstraction and Structure, David D. Riley

© Addison Wesley pub.



When a method is called that can potentially throw a checked exception,! then the code must do one of two things:

1) Be enclosed within a try instruction with a matching catch clause.

OR

2) The surrounding method must include a throws suffix.

Example ! public void cud() throws IOException { ... }

The Object of Data Abstraction and Structure, David D. Riley

© Addison Wesley pub.



7

Exceptions provide the opportunity to capture runtime errors.

Such errors are best reported in method preconditions.

Example ! /* pre: arr.length != 0 (throws ArithmeticException) * post: result = (summation of arr[0] through arr[arr.length-1]) / arr.length */ private double arrayAve(int[ ] arr) { int total == 0; for( int j = 0; j != arr.length; j++) { total = total + arr[j]; } return total / arr.length; }

The Object of Data Abstraction and Structure, David D. Riley

© Addison Wesley pub.



8