Md07 exceptions&assertion


Published on

Published in: Education, Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Md07 exceptions&assertion

  1. 1. Module 8 Exceptions & Assertions
  2. 2. <ul><li>Objectives </li></ul><ul><ul><li>• Define exceptions </li></ul></ul><ul><ul><li>• Use try, catch, and finally statements • Describe exception categories </li></ul></ul><ul><ul><li>• Identify common exceptions • Develop programs to handle your own exceptions </li></ul></ul><ul><li>• Use Assertions </li></ul><ul><li>• Distinguish appropriate and inappropriate uses of assertion. </li></ul><ul><li>• Enable assertions at runtime. </li></ul><ul><li> </li></ul>
  3. 3. <ul><li>Exception </li></ul><ul><li>An event during program execution that prevents the </li></ul><ul><li>program from continuing normally . </li></ul><ul><ul><li>like user might enter an invalid filename . </li></ul></ul><ul><ul><li>a file might contain corrupted data . </li></ul></ul><ul><ul><li>a network link could fail </li></ul></ul><ul><ul><li>a bug in the program might cause it to try to make </li></ul></ul><ul><ul><li>an illegal memory acces s </li></ul></ul><ul><ul><li>Circumstances of this type are called exception </li></ul></ul><ul><ul><li>conditions in Java. </li></ul></ul>
  4. 4. <ul><li>Call Stack </li></ul><ul><li>Suppose your program starts in method main() , </li></ul><ul><li>main() method calls method a() which calls method b(), </li></ul><ul><li>which in turn calls method c(). </li></ul><ul><li>The call stack consists of the following: </li></ul><ul><ul><li>c </li></ul></ul><ul><ul><li>b </li></ul></ul><ul><ul><li>a </li></ul></ul><ul><ul><li>main </li></ul></ul><ul><li>the last method called is at the top of the stack, while the first calling </li></ul><ul><li>method is at the bottom. </li></ul>
  5. 5. Java method call stack
  6. 6. Exception propagation Imagine a building, say, five stories high, and at each floor there is a deck or balcony. Now imagine that on each deck, one person is standing holding a baseball mitt. Exceptions are like balls dropped from person to person, starting from the roof. An exception is first thrown from the top of the stack (in other words, the person on the roof)
  7. 7. If it isn't caught by the same person who threw it (the person on the roof), it drops down the call stack to the previous method, which is the person standing on the deck one floor down. If not caught there, by the person one floor down, the exception/ball again drops down to the previous method (person on the next floor down), and so on until it is caught or until it reaches the very bottom of the call stack. This is called exception propagation. If an exception reaches the bottom of the call stack, it's like reaching the bottom of a very long drop; the ball explodes, and so does your program.
  8. 8. Throwing an Exception * When an error occurs within a method, the method creates an object and hands it off to the runtime system. * The object, called an exception object , contains information about the error, including its type and the state of the program when the error occurred. * Creating an exception object and handing it to the runtime system is called throwing an exception .
  9. 9. After a method throws an exception, the runtime system attempts to find something to handle it.This &quot;somethings&quot; to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack. call stack
  10. 10. <ul><ul><li>The runtime system searches the call stack for a method </li></ul></ul><ul><ul><li>that contains a block of code that can handle the </li></ul></ul><ul><ul><li>exception. This block of code is called an </li></ul></ul><ul><ul><li>exception handler . </li></ul></ul><ul><ul><li>The search begins with the method in which the error </li></ul></ul><ul><ul><li>occurred and proceeds through the call stack in the </li></ul></ul><ul><ul><li>reverse order in which the methods were called. </li></ul></ul><ul><ul><li>When an appropriate handler is found, the runtime </li></ul></ul><ul><ul><li>system passes the exception to the handler. </li></ul></ul>
  11. 11. Example
  12. 14. <ul><li>Checked Exception </li></ul><ul><ul><li>These are the exceptional condition that a well </li></ul></ul><ul><ul><li>written application should anticipate and recover from. </li></ul></ul><ul><ul><li>For example suppose an application prompts a user </li></ul></ul><ul><ul><li>for an input filename, the user supplies the name of </li></ul></ul><ul><ul><li>a nonexistent file, and the constructor throws </li></ul></ul><ul><ul><li> Exception. </li></ul></ul><ul><ul><li>A well-written program will catch this exception </li></ul></ul><ul><ul><li>and notify the user of the mistake </li></ul></ul><ul><ul><li>Java compiler check programmer has stated what is to </li></ul></ul><ul><ul><li>be done when they arise and because of this checking </li></ul></ul><ul><ul><li>they are called checked exception. </li></ul></ul><ul><ul><ul><li>Example </li></ul></ul></ul>
  13. 15. <ul><li>Runtime exception </li></ul><ul><ul><li>These are exceptional conditions that are internal to the </li></ul></ul><ul><ul><li>application , and that the application usually cannot anticipate </li></ul></ul><ul><ul><li>or recover from. </li></ul></ul><ul><ul><li>These usually indicate programming bugs, such as divison by zero </li></ul></ul><ul><ul><li>and invalid array indexing. </li></ul></ul><ul><li>An object of type RuntimeException may be thrown from any </li></ul><ul><li>method without being specified as part of the method's public </li></ul><ul><li>interface </li></ul>
  14. 16. <ul><li>Error </li></ul><ul><li> </li></ul><ul><ul><li>These are exceptional conditions that are external to </li></ul></ul><ul><ul><li>the application , and that the application usually cannot </li></ul></ul><ul><ul><li>anticipate or recover from. </li></ul></ul><ul><ul><li>For example , suppose that an application successfully </li></ul></ul><ul><ul><li>opens a file for input, but is unable to read the file </li></ul></ul><ul><ul><li>because of a hardware or system malfunction. </li></ul></ul><ul><ul><li>The unsuccessful read will throw </li></ul></ul><ul><ul><li>Stack overflow is also example of an Error. </li></ul></ul><ul><ul><li>You may also throw an Error yourself, for example AssertionError </li></ul></ul><ul><ul><li>Example </li></ul></ul>
  15. 17. <ul><ul><li>Why the compiler doesnot require you to catch </li></ul></ul><ul><ul><li>Runtime exceptions? </li></ul></ul><ul><ul><li>Runtime exceptions represent problems that are the </li></ul></ul><ul><ul><li>result of a programming problem such problems </li></ul></ul><ul><ul><li>include arithmetic exceptions, such as dividing by zero; </li></ul></ul><ul><ul><li>pointer exceptions,such as trying to access an object </li></ul></ul><ul><ul><li>through a null reference; and indexing exceptions, such </li></ul></ul><ul><ul><li>as attempting to access an array element through an </li></ul></ul><ul><ul><li>index that is too large or too small. </li></ul></ul><ul><ul><li> Runtime exceptions can occur anywhere in a </li></ul></ul><ul><ul><li>program , having to add runtime exceptions in every </li></ul></ul><ul><ul><li>method declaration would reduce a program's clarity. </li></ul></ul><ul><ul><li>Thus, the compiler does not require that you catch or </li></ul></ul><ul><ul><li>specify runtime exceptions </li></ul></ul>
  16. 18. <ul><li>Ways to check checked exceptions </li></ul><ul><ul><li>Two ways to check checked exceptions </li></ul></ul><ul><ul><li>Put the try block around the code that might throw the </li></ul></ul><ul><ul><li>exception and provide a corresponding catch block that </li></ul></ul><ul><ul><li>will apply to exception in question. Doing so handles </li></ul></ul><ul><ul><li>the exception </li></ul></ul><ul><ul><li>Second way is method declaration includes </li></ul></ul><ul><ul><li>a throws part that inform caller the exception </li></ul></ul><ul><ul><li>might arise. By doing so the responsibility for handling </li></ul></ul><ul><ul><li>the exception is explicitly passed to caller of method. </li></ul></ul>
  17. 19. <ul><ul><li>Three statements in handling exceptions </li></ul></ul><ul><ul><li>  </li></ul></ul><ul><ul><li>The try statement identifies a block of statements </li></ul></ul><ul><ul><li>within which an exception might be thrown. </li></ul></ul><ul><ul><li>The catch statement must be associated with a try </li></ul></ul><ul><ul><li>statement and identifies a block of statements that </li></ul></ul><ul><ul><li>can handle a particular type of exception. The </li></ul></ul><ul><ul><li>statements are executed if an exception of a particular </li></ul></ul><ul><ul><li>type occurs within the try block. </li></ul></ul><ul><ul><li>The finally statement must be associated with a try </li></ul></ul><ul><ul><li>statement and identifies a block of statements that </li></ul></ul><ul><ul><li>are executed regardless of whether or not an error </li></ul></ul><ul><ul><li>occurs within the try block. </li></ul></ul>
  18. 20. <ul><li>T he general form of these statements: </li></ul><ul><ul><ul><li>try { </li></ul></ul></ul><ul><ul><ul><li>statement(s) </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>catch ( exceptiontype name ){ </li></ul></ul></ul><ul><ul><ul><li>statement(s) </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>finally { </li></ul></ul></ul><ul><ul><ul><li>statement(s) </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><li>If the exception is thrown in try block and is caught by </li></ul></ul><ul><ul><li>matching catch block; the exception is considered to </li></ul></ul><ul><ul><li>have been handled. </li></ul></ul>
  19. 21. <ul><li>Will this codes compile </li></ul><ul><li>1. </li></ul><ul><ul><li>try{ </li></ul></ul><ul><ul><li>//do Stuff </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>System.out.println(“Hello World”); </li></ul></ul><ul><ul><li>catch(Exception e){ </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>2. </li></ul></ul><ul><ul><ul><ul><ul><li>try { </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>// do risky IO things </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>} catch (IOException e) { </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>// handle general IOExceptions </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>} catch (FileNotFoundException ex) { </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>// handle just FileNotFoundException </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>} </li></ul></ul></ul></ul></ul>
  20. 22. <ul><li>3. </li></ul><ul><li>public void doStuff() { </li></ul><ul><ul><li>try { </li></ul></ul><ul><ul><li>// risky IO things </li></ul></ul><ul><ul><li>} catch(IOException ex) { </li></ul></ul><ul><ul><li>throw ex; </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>} </li></ul>
  21. 23. <ul><li>Exception Example </li></ul><ul><ul><li>class Exc0 { </li></ul></ul><ul><ul><ul><li>public static void main(String args[]) { </li></ul></ul></ul><ul><ul><ul><ul><li>int d = 0; </li></ul></ul></ul></ul><ul><ul><ul><ul><li>int a = 42 / d; </li></ul></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>When the Java run-time system detects the attempt to </li></ul></ul><ul><ul><li>divide by zero, it constructs a new exception object and </li></ul></ul><ul><ul><li>then throws this exception. </li></ul></ul><ul><ul><li>Exception is caught by the default handler provided </li></ul></ul><ul><ul><li>by the Java run-time system. </li></ul></ul>
  22. 24. <ul><ul><li>The resulting stack trace from the default exception </li></ul></ul><ul><ul><li>handler shows how the entire call stack is displayed: </li></ul></ul><ul><ul><li>Exception in thread &quot;main&quot; java.lang.ArithmeticException: </li></ul></ul><ul><ul><li>/ by zero </li></ul></ul><ul><ul><li>at Exc0.main( </li></ul></ul>
  23. 25. <ul><li>Exception Example Revisited </li></ul><ul><ul><ul><li>class Exc2 { </li></ul></ul></ul><ul><ul><ul><li>public static void main(String args[]) { </li></ul></ul></ul><ul><ul><ul><li>int d, a; </li></ul></ul></ul><ul><ul><ul><ul><li>try { </li></ul></ul></ul></ul><ul><ul><ul><ul><li>d = 0; </li></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>a = 42 / d; </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><li>System.out.println(&quot;This will not be printed.&quot;); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>} catch (ArithmeticException e) { </li></ul></ul></ul></ul><ul><ul><ul><ul><li>System.out.println(&quot;Division by zero.&quot;); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>} </li></ul></ul></ul></ul><ul><ul><ul><ul><li>System.out.println(&quot;After catch statement.&quot;); </li></ul></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul>
  24. 26. <ul><ul><li>This program generates the following output: </li></ul></ul><ul><ul><li>Division by zero. </li></ul></ul><ul><ul><li>After catch statement. </li></ul></ul><ul><ul><li>Once an exception is thrown, program control </li></ul></ul><ul><ul><li>transfers out of the try block into the catch block. </li></ul></ul><ul><ul><li>Once the catch statement has executed, program control </li></ul></ul><ul><ul><li>continues with the next line in the program </li></ul></ul><ul><ul><li>following the entire try / catch mechanism. </li></ul></ul>
  25. 27. Flow of simple exception conditions   Exception try() catch() Behaviour No N/A N/A Normal Flow   Yes No N/A Method Termination   Yes Yes No Compile Time Error   Yes Yes Yes *Terminate try{} block *Execute body of matching Catch block *Continue Normal flow after Catch block
  26. 28. <ul><li>Catching Multiple Exception (Example ) </li></ul><ul><ul><li>Catch block catch the exceptions of the class specified </li></ul></ul><ul><ul><li>including any exceptions that are subclass of the one specified. </li></ul></ul><ul><ul><li>In order to handle more specific exceptions in one </li></ul></ul><ul><ul><li>particular catch block ,specify one exception class in one </li></ul></ul><ul><ul><li>catch block and parent class of that exception in another </li></ul></ul><ul><ul><li>catch block this way we can handle more specific </li></ul></ul><ul><ul><li>exception separately from general exception . </li></ul></ul>
  27. 29. <ul><ul><li>Under such conditions follow these two rules </li></ul></ul><ul><ul><li>1.A more specific catch block must precede a </li></ul></ul><ul><ul><li>more general one, otherwise compiler error. </li></ul></ul><ul><ul><li>Example </li></ul></ul><ul><ul><li>2.Only one catch block the most applicable one will </li></ul></ul><ul><ul><li>be executed. </li></ul></ul>
  28. 30. The throws statement If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration.
  29. 31. <ul><ul><li>What would happen when you compile and run the following </li></ul></ul><ul><ul><li>program? </li></ul></ul><ul><ul><li>class ThrowsDemo { </li></ul></ul><ul><ul><ul><li>static void throwOne() { </li></ul></ul></ul><ul><ul><ul><ul><li>System.out.println(&quot;Inside throwOne.&quot;); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>throw new IllegalAccessException(&quot;demo&quot;); </li></ul></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>public static void main(String args[]) { </li></ul></ul></ul><ul><ul><ul><li>throwOne(); </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><li>} </li></ul></ul>
  30. 32. Because the program does not specify a throws clause to declare this fact, the program will not compile. To make this example compile, you need to make two changes. 1. First, you need to declare that throwOne( ) throws IllegalAccessException. 2. Second, main( ) must define a try/catch statement that catches this exception.
  31. 33. <ul><ul><li>// This is now correct. </li></ul></ul><ul><ul><li>class ThrowsDemo { </li></ul></ul><ul><ul><ul><li>static void throwOne() throws IllegalAccessException { </li></ul></ul></ul><ul><ul><ul><ul><li>System.out.println(&quot;Inside throwOne.&quot;); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>throw new IllegalAccessException(&quot;demo&quot;); </li></ul></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>public static void main(String args[]) { </li></ul></ul></ul><ul><ul><ul><ul><li>try { </li></ul></ul></ul></ul><ul><ul><ul><ul><li>throwOne(); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>} catch (IllegalAccessException e) { </li></ul></ul></ul></ul><ul><ul><ul><ul><li>System.out.println(&quot;Caught &quot; + e); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>} </li></ul></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><li>} </li></ul></ul>
  32. 34. <ul><li>The throw statement </li></ul><ul><ul><li>Throwing an exception in its most basic form is simple . </li></ul></ul><ul><ul><li>Two steps involved in throwing an exception are </li></ul></ul><ul><ul><li>1. Create an instance of an object that is subclass of </li></ul></ul><ul><ul><li>java.lang.Throwable. </li></ul></ul><ul><ul><li>2. Use throw keyword to actually throw the exception. </li></ul></ul><ul><ul><li>  </li></ul></ul><ul><ul><li>These two are combined into a single statement </li></ul></ul><ul><ul><li>like this throw new IOException(“File not found”); </li></ul></ul><ul><li>Example </li></ul>
  33. 35. <ul><li>Finally ( </li></ul><ul><ul><li>finally creates a block of code that will be </li></ul></ul><ul><ul><li>executed after a try / catch block has completed </li></ul></ul><ul><ul><li>and before the code following the try/catch block. </li></ul></ul><ul><ul><li>The finally block will execute whether or not an </li></ul></ul><ul><ul><li>exception is thrown. </li></ul></ul><ul><ul><li>If an exception is thrown, the finally block will </li></ul></ul><ul><ul><li>execute even if no catch statement matches </li></ul></ul><ul><ul><li>the exception. </li></ul></ul><ul><ul><li>Finally block generally contain the clean up code. </li></ul></ul>
  34. 36. <ul><li>Exception and Overriding </li></ul><ul><li>Consider if you extend a class and override a method </li></ul><ul><li>the Java compiler insists that all exception classes thrown by </li></ul><ul><li>the new method be the same as subclass of the exception </li></ul><ul><li>classes thrown by original method. </li></ul><ul><li>Example </li></ul><ul><ul><li>public class BaseClass{ </li></ul></ul><ul><ul><li>public void method() throws IOException{ </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>public class LegalOne extends BaseClass{ </li></ul></ul><ul><ul><li>public void method() throws IOException{ </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>} </li></ul></ul>
  35. 37. <ul><li>public class LegalTwo extends BaseClass{ </li></ul><ul><ul><ul><li>public void method(){ </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>public class LegalThree extends BaseClass{ </li></ul><ul><li>public void method() throws EOFException, </li></ul><ul><li>MalformedURLException{ </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>public class IllegalOne extends BaseClass{ </li></ul><ul><li>public void method() throws IOException, </li></ul><ul><li>IllegalAccessException{ </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  36. 38. <ul><li> Method Overriding and Exceptions </li></ul><ul><ul><li>• Must throw exceptions that are the same class as the </li></ul></ul><ul><ul><li>exceptions being thrown by the overridden method </li></ul></ul><ul><ul><li>• May throw exceptions that are subclasses of the </li></ul></ul><ul><ul><li>exceptions being thrown by the overridden method </li></ul></ul><ul><ul><li>• If a superclass method throws multiple exceptions, </li></ul></ul><ul><ul><li>the overriding method must throw a proper subset of </li></ul></ul><ul><ul><li>exceptions thrown by the overridden method </li></ul></ul><ul><li> Example </li></ul>
  37. 39. <ul><li>Creating Your Own Exceptions </li></ul><ul><ul><li>This program creates a custom exception type. </li></ul></ul><ul><ul><li>class MyException extends Exception { </li></ul></ul><ul><ul><ul><li>private int detail; </li></ul></ul></ul><ul><ul><ul><li>MyException(int a) { </li></ul></ul></ul><ul><ul><ul><li>detail = a; </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>public String toString() { </li></ul></ul></ul><ul><ul><ul><li>return &quot;MyException[&quot; + detail + &quot;]&quot;; </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>  </li></ul>
  38. 40. <ul><ul><li>class ExceptionDemo { </li></ul></ul><ul><ul><li>static void compute(int a) throws MyException { </li></ul></ul><ul><ul><li>System.out.println(&quot;Called compute(&quot; + a + &quot;)&quot;); </li></ul></ul><ul><ul><ul><li>if(a > 10) </li></ul></ul></ul><ul><ul><ul><ul><li>throw new MyException(a); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>System.out.println(&quot;Normal exit&quot;); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>} </li></ul></ul></ul></ul><ul><ul><ul><li>public static void main(String args[]) { </li></ul></ul></ul><ul><ul><ul><ul><li>try { </li></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>compute(1); </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>compute(20); </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><li>} catch (MyException e) { </li></ul></ul></ul></ul><ul><ul><ul><ul><li>System.out.println(&quot;Caught &quot; + e); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>} </li></ul></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><li>} </li></ul></ul>
  39. 41. Assertions An assertion is a statement in the Java programming language that enables you to test your assumptions about your program. Suppose you assume that a number passed into a method will never be negative,to validate your assumption,you write 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(&quot;Yikes! num is a negative number! &quot; + num);} }
  40. 42. <ul><li>Using Assertions write the earlier code as </li></ul><ul><ul><li>private void methodA(int num) { </li></ul></ul><ul><ul><ul><li>assert (num>=0); </li></ul></ul></ul><ul><ul><ul><li>// throws an AssertionError if this test isn't true </li></ul></ul></ul><ul><ul><ul><li>useNum(num + x); </li></ul></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>So each assertion contains a boolean expression that will be true </li></ul><ul><li>when the assertion executes. If it is not true, the system will throw </li></ul><ul><li>an error. </li></ul><ul><li>Assertions work quite simply. You always assert that something </li></ul><ul><li>is true. If it is, no problem. Code keeps running. But if your assertion </li></ul><ul><li>turns out to be wrong (false), then AssertionError is thrown </li></ul>
  41. 43. Forms of Assertion The assertion statement has two forms. The first, simpler form 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 detail message. Example private void doStuff() { assert (y > x); // more code assuming y is greater than x }
  42. 44. 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. The second form assert Expression1 : Expression2 ; Use this version of the assert statement to provide a detail message for the AssertionError. The system passes the value of Expression2 to the appropriate AssertionError constructor, which uses the string representation of the value as the error's detail message.
  43. 45. <ul><li>Example </li></ul><ul><ul><li>private void doStuff() { </li></ul></ul><ul><ul><li>assert (y > x): &quot;y is &quot; + y + &quot; x is &quot; + x; </li></ul></ul><ul><ul><li>// more code assuming y is greater than x </li></ul></ul><ul><ul><li>} </li></ul></ul>
  44. 46. <ul><li>Appropriate and Inappropriate uses of Assertion </li></ul><ul><li>Situations where it is good to use assertions. </li></ul><ul><ul><li>Internal Invariants </li></ul></ul><ul><ul><li>Control-Flow Invariants </li></ul></ul><ul><ul><li>Preconditions & Postconditions </li></ul></ul>
  45. 47. <ul><li>Internal Invariants </li></ul><ul><li>Before assertions were available, many programmers used </li></ul><ul><li>comments to indicate their assumptions concerning a program's </li></ul><ul><li>behavior. </li></ul><ul><ul><li>if (i % 3 == 0) { </li></ul></ul><ul><ul><li>... </li></ul></ul><ul><ul><li>} else if (i % 3 == 1) { </li></ul></ul><ul><ul><li>... </li></ul></ul><ul><ul><li>} else { // We know (i % 3 == 2) </li></ul></ul><ul><ul><li>... </li></ul></ul><ul><ul><li>} </li></ul></ul>
  46. 48. <ul><li>Rewriting the previous if-statement using assertions </li></ul><ul><ul><li>if (i % 3 == 0) { </li></ul></ul><ul><ul><li>... </li></ul></ul><ul><ul><li>} else if (i % 3 == 1) { </li></ul></ul><ul><ul><li>... </li></ul></ul><ul><ul><li>} else { assert i % 3 == 2 : i; </li></ul></ul><ul><ul><li>... </li></ul></ul><ul><ul><li>} </li></ul></ul>
  47. 49. <ul><li>Suppose the following switch statement appears in a program that </li></ul><ul><li>handles playing cards: </li></ul><ul><ul><li>switch(suit) { </li></ul></ul><ul><ul><li>case Suit.CLUBS: </li></ul></ul><ul><ul><li>... </li></ul></ul><ul><ul><li>break; </li></ul></ul><ul><ul><li>case Suit.DIAMONDS: </li></ul></ul><ul><ul><li>... </li></ul></ul><ul><ul><li>break; </li></ul></ul><ul><ul><li>case Suit.HEARTS: </li></ul></ul><ul><ul><li>... </li></ul></ul><ul><ul><li>break; </li></ul></ul><ul><ul><li>case Suit.SPADES: </li></ul></ul><ul><ul><li>... </li></ul></ul><ul><ul><li>} </li></ul></ul>
  48. 50. It probably indicates an assumption that the suit variable will have one of only four values. To test this assumption, add the following default case: default: assert false : suit; If the suit variable takes on another value and assertions are enabled, the assert will fail and an AssertionError will be thrown. Alternative is: default: throw new AssertionError(suit); This alternative offers protection even if assertions are disabled
  49. 51. Control-Flow Invariants Place an assertion at any location you assume will not be reached. The assertions statement to use is: assert false; For example, suppose you have a method that looks like this: void foo() { for (...) { if (...) return; } // Execution should never reach this point!!! }
  50. 52. Replace the final comment so that the code now reads: void foo() { for (...) { if (...) return; } assert false; // Execution should never reach this point! }
  51. 53. Preconditions & Postconditions By convention, preconditions on public methods are enforced by explicit checks that throw particular, specified exceptions. For example: public void setRefreshRate(int rate) { // Enforce specified precondition in public method if (rate <= 0 || rate > MAX_REFRESH_RATE) throw new IllegalArgumentException(&quot;Illegal rate: &quot; + rate); setRefreshInterval(1000/rate); } This convention is unaffected by the addition of the assert construct.
  52. 54. <ul><li>Don't Use assertions to validate arguments to a Public Method </li></ul><ul><li>The following is an inappropriate use of assertions: </li></ul><ul><ul><li>public void doStuff(int x) { </li></ul></ul><ul><ul><li>assert (x > 0); // inappropriate ! </li></ul></ul><ul><ul><li>// do things with x </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>A public method might be called from code that you don't control </li></ul><ul><li>because public methods are part of your interface to the outside </li></ul><ul><li>world, you're supposed to guarantee that any constraints on the </li></ul><ul><li>arguments will be enforced by the method itself. </li></ul><ul><li>But since assertions aren't guaranteed to actually run the </li></ul><ul><li>enforcement won't happen if assertions aren't enabled. </li></ul>
  53. 55. However assertion can be used to test a non public method's precondition. If you write a private method, you almost certainly wrote (or control) any code that calls it. When you assume that the logic in code calling your private method is correct, you can test that assumption with an assertion as follows: private void doMore(int x) { assert (x > 0); // do things with x } Remember You're certainly free to compile assertion code with an inappropriate validation of public arguments,
  54. 56. Don't Use assertions to validate Command-Line arguments If your program requires command-line arguments, you'll probably use the exception mechanism to enforce them.
  55. 57. <ul><li>Identifier vs Keyword </li></ul><ul><li>Prior to version 1.4, </li></ul><ul><ul><li>int assert = getInitialValue(); </li></ul></ul><ul><ul><li>if (assert == getActualResult()) { </li></ul></ul><ul><ul><li>// do something </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>assert is used as an identifier. </li></ul><ul><li>But you cannot use a keyword/reserved word as an identifier, </li></ul><ul><li>and beginning with version 1.4, assert is a keyword. </li></ul><ul><li>You can use assert as a keyword or as an identifier, but not both. </li></ul>
  56. 58. If using a Java 1.4 compiler , and also using assert as a keyword (in other words, you're actually trying to assert something in your code), then you must explicitly enable assertion-awareness at compile time, as follows: javac -source 1.4 com/geeksanonymous/ The Java 5 compiler will use the assert keyword by default, the compiler will generate an error message if it finds the word assert used as an identifier. However, you can tell the compiler that you're giving it an old piece of code to compile, javac -source 1.3
  57. 59. What will happen in the following case Suppose the program is using the assert as an identifier and you compile using javac -source 1.4 Will the code compile?
  58. 60. In this case, the compiler will issue errors when it discovers the word assert used as an identifier. Using Java 5 Compiler
  59. 61. Enable Assertions Programmers of certain critical systems might wish to ensure that assertions are not disabled in the field. The following static initialization idiom prevents a class from being initialized if its assertions have been disabled: static { boolean assertsEnabled = false; assert assertsEnabled = true; // Intentional side effect!!! if (!assertsEnabled) throw new RuntimeException(&quot;Asserts must be enabled!!!&quot;); }
  60. 62. <ul><li>Enabling and Disabling Assertions </li></ul><ul><li>By default, assertions are disabled at runtime. </li></ul><ul><li>Two command-line switches allow you to selectively enable or </li></ul><ul><li>disable assertions. </li></ul><ul><li>To enable assertions use the -enableassertions, or -ea </li></ul><ul><ul><li>java -ea com.geeksanonymous.TestClass </li></ul></ul><ul><ul><li>java -enableassertions com.geeksanonymous.TestClass </li></ul></ul><ul><li>To disable assertions use the -disableassertions or -da, </li></ul><ul><ul><li>java -da com.geeksanonymous.TestClass </li></ul></ul><ul><ul><li>java -disableassertions com.geeksanonymous.TestClass </li></ul></ul>
  61. 63. Selective Enabling and Disabling no arguments    Enables or disables assertions in all classes except system classes. packageName ...    Enables or disables assertions in the named package and any subpackages. className    Enables or disables assertions in the named class
  62. 64. For example, java -ea:com.wombat.fruitbat BatTutor The following command runs a program, BatTutor, with assertions enabled in only package com.wombat.fruitbat and its subpackages: -enablesystemassertions, or -esa. To enable assertions in all system classes. java -ea -da:com.geeksanonymous.Foo this tells the JVM to enable assertions in general, but disable them in the class com.geeksanonymous.Foo. java -ea -da:com.geeksanonymous... tells the JVM to enable assertions in general, but disable them in the package com.geeksanonymous, and all of its subpackages!