Top Banner

of 26

Chapter8 Exceptions&Assertions

May 29, 2018

Download

Documents

ramji013
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/8/2019 Chapter8 Exceptions&Assertions

    1/26

    Exception Handling and Assertions

  • 8/8/2019 Chapter8 Exceptions&Assertions

    2/26

    Objectives

    At the end of the lesson, you should be able to:

    Explain the basic concepts of exception handling.

    Write code to catch and handle exceptions.

    Write code to throw exceptions.

    Create your own exceptions.

    Explain the concepts of assertion.

  • 8/8/2019 Chapter8 Exceptions&Assertions

    3/26

    What is an Exception?

    Exceptional event

    Error that occurs during runtime

    Cause normal program flow to be disrupted

    Examples

    Divide by zero errors

    Accessing the elements of an array beyond its range

    Invalid input

    Hard disk crash

    Opening a non-existent file

    Heap memory exhausted

    Exception HandlingWhat is an Exception?

    Benefits of Exception Handling

    Exception Class Hierarchy

    Types of Exception

    The Catch or Specify Requirement

    Catching Exceptions with try-catch

    Catching Exceptions with try-catch-finally

    Specifying the Exceptions Thrown by a Method

    Throwing Exceptions

    Creating Your Own Exception Class

  • 8/8/2019 Chapter8 Exceptions&Assertions

    4/26

    Exception: An exception is an event, which occurs during the execution of a program thatdisrupts the normal flow of the program's instructions.

    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 .It containabout 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.

    After a method throws an exception, the runtime system attempts to find something 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.

    The runtime system searches the call stack for a method that contains a block of code that

    can handle the exception. This block of code is called an exception handler. The exception

    handler chosen is said to catch the exception.

    Benefits of Exception Handling

    Separating Error-Handling code from regular business logic code

    Propagating errors up the call stack

    Grouping and differentiating error types

  • 8/8/2019 Chapter8 Exceptions&Assertions

    5/26

    Separating Error-Handling code from regular business logic code -In traditional

    programming, error detection,reporting, and handling often lead to confusing code.

    Exceptions enable you to write the main flow of your code and to deal with the exceptional cases

    elsewhere.

    Note that exceptions don't spare you the effort of doing the work of detecting, reporting, and

    handling errors, but they do help you organize the work more effectively.

    Propagating errors up the call stack-A second advantage of exceptions is the ability to

    propagate error reporting up the call stack of methods.

    For Example, Suppose that the readFile method is the fourth method in a series of nested method

    calls made by the main program: method1 calls method2, which calls method3, which finally

    calls readFile. Suppose also that method1 is the only method interested in the errors that might

    occur within readFile. Recall that the Java runtime environment searches backward through the

    call stack to find any methods that are interested in handling a particular exception. A method

    can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to

    catch it. Hence, only the methods that care about errors have to worry about detecting errors.

    Grouping and differentiating error types-A method can catch an exception based on its group

    or general type by specifying any of the exception's superclasses in the catch statement.

    Exception Class Hierarchy

    The figure below illustrates the class hierarchy of the Throwable class and its

    most significant subclasses.

  • 8/8/2019 Chapter8 Exceptions&Assertions

    6/26

    Throwable class

    Root class of exception classes

    Subclass of the Object class.

    The objects that inherit from the Throwable class include direct descendants (objects

    that inherit directly from the Throwable class) and indirect descendants (objects that

    inherit from children or grandchildren of the Throwable class).

    checked exception :

    These are exceptional conditions that a well-written application should anticipate and

    recover from.Checked exceptions are subjectto the Catch or Specify Requirement

    For example, suppose an application prompts a user for an input file name, then opens the

    file by passing the name to the constructor for java.io.FileReader. sometimes the user supplies

    the name of a nonexistent file, and the constructor throws java.io.FileNotFoundException. A

    well-written program will catch this exception and notify the user of the mistake, possibly

    prompting for a corrected file name.

    Types of Exception

    1. Checked Exception.

    It occurs in a java program due to invalid user input, network connectivity problem or

    database problems.

    2. Unchecked Exception.

    It occurs because of programming errors, such as invalid arguments passed to a public

    method. The java complier does not check the unchecked exceptions during program compilation.

    i. Error

    ii. Runtime exception

  • 8/8/2019 Chapter8 Exceptions&Assertions

    7/26

    Error: Used by the Java run-time system to handle errors occurring in the run-time

    environment.Generally beyond the control of user programs

    Examples

    Out of memory errors Hard disk crash

    For example, suppose that an application successfully opens a file for input, but is unable

    to read the file because of a hardware or system malfunction. The unsuccessful read will throw

    java.io.IOError.

    Runtime exception : Conditions that user programs can reasonably deal with. Usually the result

    of some flaws in the user program code

    Examples

    Division by zero error Array out-of-bounds error

    For example, consider the application described previously that passes a file name to the

    constructor for FileReader. If a logic error causes a null to be passed to the constructor, the

    constructor will throw NullPointerException.

    The Catch or Specify Requirement

    Java code that might throw certain exceptions must be enclosed by either of the following:

    o Catching and Handling Exceptions.

    Try block

    Catch block

    Finally block

    o Specifying the Exceptions Thrown by a Method.

    Code that fails to honor the Catch or Specify Requirement will not compile.

    http://java.sun.com/docs/books/tutorial/essential/exceptions/declaring.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/declaring.html
  • 8/8/2019 Chapter8 Exceptions&Assertions

    8/26

    Try statement that catches the exception. The try must provide a handler for the exception, as

    described inCatching and Handling Exceptions.

    A method specifies that it can throw the exception. The method must provide a throws clause

    that lists the exception, as described in Specifying the Exceptions Thrown by a Method.

    Catching Exceptions with try-catchThetry Block:

    The first step in constructing an exception handler is to enclose the code that might throw an

    exception within a try block.

    The catch Blocks:

    You associate exception handlers with a try block by providing one or more catch blocks directly

    after the try block.

    Syntax: Single Exceptiontry {

    } catch ( ExceptionType name) {

    }

    Syntax: Multiple Exceptionstry {

    } catch ( ExceptionType1 name)

    {

    } catch (ExceptionType 2 name)

    {

    }

    http://java.sun.com/docs/books/tutorial/essential/exceptions/handling.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/declaring.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/declaring.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/handling.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/declaring.html
  • 8/8/2019 Chapter8 Exceptions&Assertions

    9/26

    The segment in the example labeled code contains one or more legal lines of code that could

    throw an exception.

    The programmer can associate exception handlers with a try block by providing atleast one catch

    block or finally block, without this we cant associate exception handler.

    Each catch block is an exception handlerand handles the type of exception indicated by its

    argument. The argument type, ExceptionType, declares the type of exception that the handler can

    handle and must be the name of a class that inherits from the Throwable class. The handler can

    refer to the exception with name.

    The catch block contains code that is executed if and when the exception handler is invoked. The

    runtime system invokes the exception handler when the handler is the first one in the call stack

    whoseExceptionType matches the type of the exception thrown. The system considers it a match

    if the thrown object can legally be assigned to the exception handler's argument.

    Example ForThe try-catch Statements

  • 8/8/2019 Chapter8 Exceptions&Assertions

    10/26

    class DivByZero {

    public static void main(String args[]) { try {

    System.out.println(3/0);

    System.out.println (Please print me.); } catch (ArithmeticException exc) {

    //Division by zero is an ArithmeticException

    System.out.println(exc);

    }

    System.out.println (After exception.);

    }

    }

    Example ForMultiple catch

    class MultipleCatch {

    public static void main(String args[]) {

    try {

    int den = Integer.parseInt(args[0]);

    System.out.println(3/den);

    } catch (ArithmeticException exc) {

    System.out.println(Divisor was 0.);

    } catch (ArrayIndexOutOfBoundsException exc2) {

    System.out.println(Missing argument.);

    }

    System.out.println(After exception.);}}

  • 8/8/2019 Chapter8 Exceptions&Assertions

    11/26

    Example ForNested trys

    class NestedTryDemo {

    public static void main(String args[]){try {

    int a = Integer.parseInt(args[0]);

    try {

    int b = Integer.parseInt(args[1]);System.out.println(a/b);

    } catch (ArithmeticException e) {

    System.out.println(Div by zero error!");

    }

    } catch (ArrayIndexOutOfBoundsException) {

    System.out.println(Need 2 parameters!");

    }}

    }

    Example ForNested trys with Method

    class NestedTryDemo2 {static void nestedTry(String args[]) {

    try {

    int a = Integer.parseInt(args[0]);

    int b = Integer.parseInt(args[1]);System.out.println(a/b);

    } catch (ArithmeticException e) {System.out.println("Div by zero error!");

    }

    }

    public static void main(String args[]){

    try {

    nestedTry(args);

    } catch (ArrayIndexOutOfBoundsException e) {

    System.out.println("Need 2 parameters!");

    }

    }

    }

    Catching Exceptions with try-catch-finally

    The finally Block:

    The finally blockalways executes when the try block exits. This ensures that the finally block is

    executed even if an unexpected exception occurs.

    Syntax:try {

    } catch ( ExceptionType1 name) {

    } catch (ExceptionType 2 name) {

    } finally {

    }

  • 8/8/2019 Chapter8 Exceptions&Assertions

    12/26

    If the JVM exits while the try or catch code is being executed, then the finally block will

    not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the

    finally block will not execute even though the application as a whole continues.

    Note: The finally block is a key tool for preventing resource leaks. When closing a file or

    otherwise recovering resources, place the code in a finally block to insure that resource is always

    recovered.

    Rules for try, catch and finally Blocks :

    1. For each try block there can be zero or more catch blocks, but only one finally block.

    2. The catch blocks and finally block must always appear in conjunction with a try block.

    3. A try block must be followed by either at least one catch block or one finally block.

    4. The order exception handlers in the catch block must be from the most specific exception

    Example ForThe try-catch -finally Statements

    import java.io.*;

    public class ListOfNumbers {

  • 8/8/2019 Chapter8 Exceptions&Assertions

    13/26

    public static void main(String arg[]){

    PrintWriter out = null;

    try {

    System.out.println("Entering try statement");

    out = new PrintWriter(

    new FileWriter("OutFile.txt"));

    out.println("Example for finally blocks");

    } catch (IOException e) {

    System.err.println("Caught IOException: "+ e.getMessage());

    } finally {

    if (out != null) {

    System.out.println("Closing PrintWriter");

    out.close();

    } else {

    System.out.println("PrintWriter not open");

    }

    }

    }

    }

    Specifying the Exceptions Thrown by a Method

    A method is required to either catch or list all exceptions it might throw

    Except for ErrororRuntimeException, or their subclasses

    If a method may cause an exception to occur but does not catch it, then it must say so using thethrows keyword

    Applies to checked exceptions only

    Syntax:

    () throws {

    }

  • 8/8/2019 Chapter8 Exceptions&Assertions

    14/26

    The throws statement species the list of exception that has thrown by a method. If a method is

    capable of raising an exception that is does not handle, it must specify the exception has to be

    handle by the callingmethod, this is done by using the throw statement.

    Example for Exceptions Thrown by a Method:

    class ThrowingClass {

    static void meth() throws ClassNotFoundException{

    throw new ClassNotFoundException ("demo");

  • 8/8/2019 Chapter8 Exceptions&Assertions

    15/26

    }

    }

    class ThrowsDemo {public static void main(String args[]) {

    try {

    ThrowingClass.meth();} catch (ClassNotFoundException e) {

    System.out.println(e);

    }}

    }

    Output:

    java.lang.ClassNotFoundException: demo

    Throwing Exceptions

    Java allows you to throw exceptions (generate exceptions)

    throw ;

    We can also create your own exception classes.

    To represent problems that can occur within the classes you write.

    We can also create chainedexceptions.

    An application often responds to an exception by throwing another exception.

  • 8/8/2019 Chapter8 Exceptions&Assertions

    16/26

    All methods use the throw statement to throw an exception. The throw statement requires

    a single argument: a throwable object. Throwable objects are instances of any subclass of the

    Throwable class.

    Chained Exceptions- In effect, the first exception causes the second exception. It can be very

    helpful to know when one exception causes another. Chained Exceptions help the programmer

    do this. The following example shows how to use a chained exception.

    try {

    } catch (IOException e) {throw new SampleException("Other IOException", e);

    }

    stack trace It provides information on the execution history of the current thread and lists the

    names of the classes and methods that were called at the point when the exception occurred. A

    stack trace is a useful debugging tool that you'll normally take advantage of when an exception

    has been thrown.

    Example for Throwing Exceptions :

    class ThrowDemo {

    public static void main(String args[]){

    String input = invalid input;try {

  • 8/8/2019 Chapter8 Exceptions&Assertions

    17/26

    if (input.equals(invalid input)) {

    throw new RuntimeException("throw demo");

    } else {System.out.println(input);

    }

    } catch (RuntimeException e) {System.out.println("Exception caught:" + e);

    }

    }}

    Output:

    Exception caught: java.lang.RuntimeException: throw demo

    Creating Your Own Exception Class

    Steps to follow

    Create a class that extends theException class

    Customize the class

    Members and constructors may be added to the class

    Sytntax:

    Public class extends Exception {..}

  • 8/8/2019 Chapter8 Exceptions&Assertions

    18/26

    Java defines several built-in classes for exception handling. All these classes are a part of

    the java.lang package which is automatically imported. That is why, while throwing an exception

    you did not specifically include any package for exception classes.

    Apart from the built-in exception classes you can define your own exception classes. This

    is very useful when you want to define exception types which are having a behavior different

    from the standard exception type, particularly when you want to do validations in your

    application.

    You can create muttiple exceptions for different cirumstances in your code, if your code

    access different files. You can throw a different exception for each file.This approach is useful

    for several reasons:

    You can handle each exception differently.

    If your exception handlers print out the Exception, this gives you or your users more

    information about where the exception occurred.

    You can customize your exception.

    Example for Creating Your Own Exception Class

    class NumberRangeException extends Exception { NumberRangeException () {

    super("Enter a number between 20 and 100");

  • 8/8/2019 Chapter8 Exceptions&Assertions

    19/26

    }

    }

    public class My_Exception {public static void main (String args [ ]) {

    try {

    int x = 10;if (x < 20 || x >100) throw new NumberRangeException( );

    } catch (NumberRangeException e) {System.out.println (e);

    }}

    }

    Assertion

    What are Assertions?

    Compiling Files that useAssertions

    Enabling and Disabling Assertions

    Where You Should Not Use Assertions

    Where It Is Good To Use Assertions

  • 8/8/2019 Chapter8 Exceptions&Assertions

    20/26

    What are Assertions? Statements that let a programmer test assumptions about the state of a program.

    Boolean expressions that you believe are true when the assertion executes. If false, system

    throws an error.

    By verifying expressions, INCREASE confidence that program is error free.

    Manual approach: Programmer must insert assertions into a program.

    Two forms of the assert statement

    Usualform

    Syntax: assert ;

    Abbreviatedform

    Syntax: assert : ;

  • 8/8/2019 Chapter8 Exceptions&Assertions

    21/26

    An assertion has a Boolean expression that, if evaluated as false, indicates a bug in the

    code. This mechanism provides a way to detect when a program starts falling into an inconsistent

    state. Assertions are excellent for documenting assumptions and invariants about a class.

    In Usualform, if the Booelan Expression evalutates to false, then an AssertionError is

    thrown.This error should not be caught,and the program should be terminated abnormally.

    In Abbreviatedform, an assert statement has two parts separated by a colon. The boolean

    condition must be true for execution to continue. If it is false, an AssertionError is thrown, which

    terminates execution and display the message string.

    void noReturn() { }

    int aReturn() { return 1; }

    void go() {int x = 1; boolean b = true;

    legal assert statements Illegal assert statementsassert(x == 1);

    assert(b);

    assert true;

    assert(x == 1) : x;

    assert(x == 1) : aReturn();

    assert(x == 1) : new ValidAssert();

    assert(x = 1); // none of these are booleans

    assert(x);

    assert 0;assert(x == 1) : ; // none of these return a value

    assert(x == 1) : noReturn();

    assert(x == 1) : ValidAssert va;

    Compiling Files that useAssertions

    You can use assert as a keyword or as an identifier, but not both.

    The Java 5 compiler will use the assert keyword by default.

    Command Line If assert Is anIdentifier If assert Is a Keyword

    javac -source 1.3

    TestAsserts.java

    Code compiles withwarnings.

    Compilation fails.

    javac -source 1.4

    TestAsserts.java

    Compilation fails. Code compiles.

    javac -source 1.5

    TestAsserts.java

    Compilation fails. Code compiles.

    javac -source 5

    TestAsserts.java

    Compilation fails. Code compiles

    javac -source 5

    TestAsserts.java

    Compilation fails. Code compiles

    javac Compilation fails. Code compiles

  • 8/8/2019 Chapter8 Exceptions&Assertions

    22/26

    If you want to use assertions, you have to think first about how to compile with assertions

    in your code, and then about how to run with assertions enabled.

    Identifier vs. Keyword

    Prior to version 1.4, you might very well have written code like this:

    int assert = getInitialValue();

    if (assert == getActualResult()) {

    // do something

    }

    Notice that in the preceding code, assert is used as an identifier. That's not a problem prior to 1.4.

    But you cannot use a keyword/reserved word as an identifier, and beginning with version 1.4,

    assert is a keyword.

    If you want to tell the compiler to use Java 5 rules you can do one of three things: omit the

    -source option, which is the default, or add one of two source options:

    Enabling and Disabling Assertions

    Assertions can be turned-on and off.

    By default, assertions are turned off

    To enable assertions:

    java ea classname java ea: classname

    or

    java enableassertions classname

    To disable assertions:

    java da classname java da: classname

    or

    java disableassertions classname

    To en/disable system assertions: -esa or -dsa

  • 8/8/2019 Chapter8 Exceptions&Assertions

    23/26

    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.

    Selective Enabling and Disabling

    The command-line switches for assertions can be used in various ways:

    With no arguments (as in the preceding examples) Enables or disables assertions in all

    classes, except for the system classes.

    java ea orjava enableassertions java da orjava -disableassertions

    With a package name Enables or disables assertions in the package specified, and any

    packages below this package in the same directory hierarchy (more on that in a moment).

    java -ea:packagename.subpackage

    With a class name Enables or disables assertions in the class specified.

    Enable assertions in general, but disable assertions in system classes - java -ea dsaEnable assertions in general,but disable assertions in package - java -ea -da:packagenameWhere You Should Not Use Assertions

    Do Use Assertions to Validate Arguments to Public Method and PrivateMethod.

    Do not use assertions to do any work that your application requires for

    correct operation.

  • 8/8/2019 Chapter8 Exceptions&Assertions

    24/26

    1. Argument checking is typically part of the published specifications (or contract) of a method,

    and these specifications must be obeyed whether assertions are enabled or disabled. Another

    problem with using assertions for argument checking is that erroneous arguments should result in

    an appropriate runtime exception (such as IllegalArgumentException). An assertion failure will

    not throw an appropriate exception.

    2. Because assertions may be disabled, programs MUST NOT assume that the boolean

    expression contained in an assertion will be evaluated. Violating this rule has dire consequences.

    For example, suppose you wanted to remove all of the null elements from a list names, and knew

    that the list contained one or more nulls. It would be wrong to do this:

    // Broken! - action is contained in assertion

    assert names.remove(null);

    The program would work fine when asserts were enabled, but would fail when they were

    disabled, as it would no longer remove the null elements from the list. The correct idiom is to

    perform the action before the assertion and then assert that the action succeeded:

    Where It Is Good To Use Assertions

    Internal Invariants

    You should now use an assertion whenever you would have written a comment that asserts aninvariant.

    An assertion is a switch statement with no default case.

    Control-Flow Invariants

    Place an assertion at any location you assume will not be reached

    Preconditions, Postconditions, and Class Invariants

    It can help support an informal design-by-contract style of programming.

  • 8/8/2019 Chapter8 Exceptions&Assertions

    25/26

    Internal Invariants : Example

    if (i % 3 == 1) {...

    } else {

    assert i % 3 == 2 : i;

    ...}

    Control-Flow Invariants : Example

    void foo() {

    for (...) {

    if (...) return;

    }

    assert false; // Execution should never reach this point!

    }

    Preconditions, Postconditions, and Class Invariants:

    You can test postcondition with assertions in both public and nonpublic methods.

    A class invariants is a type of internal invariant that applies to every instance of a class at all

    times, except when an instance is in transition from one consistent state to another. A class

    invariant can specify the relationships among multiple attributes, and should be true before and

    after any method completes.

    Switch statement1. default:

    2. assert false : suit;

  • 8/8/2019 Chapter8 Exceptions&Assertions

    26/26