Session3-Exceptions Assertions

26
Session3 – Exceptions & Assertions

Transcript of Session3-Exceptions Assertions

Page 1: Session3-Exceptions Assertions

Session3 – Exceptions & Assertions

Page 2: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Exception Hierarchy

Page 3: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Error & Exception

Error represent unusual situations that are not caused by program errors, and indicate things that would not normally happen during program execution, such as the JVM running out of memory.

The term "exception" means "exceptional condition" and is an occurrence that alters the normal program flow.

Page 4: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Handling Exception

- Using try and catch block

- Using throws

Page 5: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Try /catch block

The try is used to define a block of code in which exceptions may occur. This block of code is called guarded region (which really means "risky code goes here"). One or more catch clauses match a specific exception (or group of exceptions—more on that later) to a block of code that handles it.

try {

// Put code here that might cause some kind of exception. // We may have many code lines here or just one.

}catch(MyFirstException) {

// Put code here that handles this exception.

}

Page 6: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

finally

A finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not.

try {

// Put code here that might cause some kind of exception. // We may have many code lines here or just one.

}catch(MyFirstException) {

// Put code here that handles this exception.

}finally{

// Put code here to release any resource we// allocated in the try clause.}

Page 7: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Exam hint

It is illegal to use a try clause without either a catch clause or a finally clause. A try clause by itself will result in a compiler error. Any catch clauses must immediately follow the try block. Any finally clause must immediately follow the last catch clause (or it must immediately follow the try block if there is no catch). It is legal to omit either the catch clause or the finally clause, but not both.

Page 8: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

The following won’t compile:

try {

// do stuff

}

System.out.print("below the try"); //Illegal!

catch(Exception ex) {

}

Page 9: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Using throws clause

e.g.

void doMore throws IOException(){

……

}

void myFunction() throws MyException1, MyException2 {

// code for the method here

}

Page 10: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Using throw keyword

e.g.

void doStuff() {

try{

doMore();

}catch(IOException e){

}

}

void doMore() {

throw new IOException();

}

Page 11: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Handling an Entire Class Hierarchy of Exceptions

Resist the temptation to write a single catchall exception handler such as the following:

try {

// some code

}

catch (Exception e) {

e.printStackTrace();

}

Instead use the following block of code:

try{

}catch(FileNotFoundException fe){}

catch(IOException i){}

Page 12: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Contd…

try {

// do risky IO things

} catch (IOException e) {

// handle general IOExceptions

} catch (FileNotFoundException ex) {

// handle just FileNotFoundException

}

You'll get a compiler error something like this:

TestEx.java:15: exception java.io.FileNotFoundException has already been caught

} catch (FileNotFoundException ex) {}

Page 13: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Handling an Entire Class Hierarchy of Exceptions

Resist the temptation to write a single catchall exception handler such as the following:

try {

// some code

}

catch (Exception e) {

e.printStackTrace();

}

Instead use the following block of code:

try{

}catch(FileNotFoundException fe){}

catch(IOException i){}

Page 14: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

What is an assertion?

An assertion is a statement in Java that enables you to test your assumptions about your program.

Each assertion contains a boolean expression that you believe will be true when the assertion executes.

By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors

Page 15: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

private void methodA(int num) {

if (num >= 0) {

useNum(num + x);

} else { // num must be < 0

// This code should never be reached!

System.out.println("Yikes! num is a negative number! "

+ num);

}

}

Using Assertion

private void methodA(int num) {

assert (num>=0); // throws an AssertionError

// if this test isn't true

useNum(num + x);

}

Page 16: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Assertions are typically enabled when an application is being tested and

debugged, but disabled when the application is deployed. The assertions are

still in the code, although ignored by the JVM, so if you do have a deployed

application that starts misbehaving, you can always choose to enable

assertions in the field for additional testing.

Page 17: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Simple Assertion Form

The assertion statement has two forms The first is:

assert Expression1 ; Where Expression1 is a boolean expression When the system runs the assertion,

it evaluates Expression1 and if it is false throws an AssertionError with no details

Page 18: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Complex Assertion Form

The second form of the assertion statement is: assert Expression1 : Expression2 ;

where: – Expression1 is a boolean expression– Expression2 is an expression that has a value – It cannot invoke of a method that is declared void

Page 19: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Complex Assertion Form, cont.

Use the second version of the assert statement to provide a detailed message for the AssertionError

The system passes the value of Expression2 to the appropriate AssertionError constructor, which uses the string error message

The purpose of the message is to communicate the reason for the assertion failure

Page 20: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

When an Assertion Fails

Assertion failures are labeled in stack trace with the file and line number from which they were thrown

Second form of the assertion statement should be used in preference to the first when the program has some additional information that might help diagnose the failure

Page 21: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Compiler Directives

For the javac compiler to accept code with assertions, use this command-line option:

-source 1.4 For example:

javac -source 1.4 MyClass.java

Page 22: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Running with Assertions

Assertions may be enabled and disabled Assertions are, by default, disabled at run-time

Page 23: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Enabling Assertions at Runtime

java -ea com.geeksanonymous.TestClass

or

java -enableassertions com.geeksanonymous.TestClass

Disabling Assertions at Runtime

java -da com.geeksanonymous.TestClass

or

java -disableassertions com.geeksanonymous.TestClass

Page 24: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Arguments

no arguments    Enables or disables assertions in all classes

packageName...    Enables or disables assertions in the named package and any subpackages

className   Enables or disables assertions in the named class

Page 25: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Using Assertions Appropriately

Don't Use Assertions to Validate Arguments to a Public Method Do Use Assertions to Validate Arguments to a Private Method Don't Use Assert Expressions that Can Cause Side Effects!

The following would be a very bad idea:

public void doStuff() {

assert (modifyThings());

// continues on

}

public boolean modifyThings() {

y = x++;

return true;

}

Page 26: Session3-Exceptions Assertions

© 2009 Deloitte Touche Tohmatsu

Q&A