2 exception handling1

Upload: jocansino

Post on 07-Apr-2018

222 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 2 Exception Handling1

    1/29

    Exception Handling

  • 8/3/2019 2 Exception Handling1

    2/29

    Lecture Objectives

    To learn how to throw exceptions

    To be able to design your own exception

    classes To understand the difference between checked

    and unchecked exceptions

    To learn how to catch exceptions

    To know when and where to catch an exception

  • 8/3/2019 2 Exception Handling1

    3/29

    Error Handling

    Traditional approach: Method returns errorcode

    Problem: Forget to check for error code

    Failure notification may go undetected

    Problem: Calling method may not be able todo anything about failure

    Program must fail too and let its caller worry about it

    Many method calls would need to be checked

    Continued

  • 8/3/2019 2 Exception Handling1

    4/29

    Instead of programming for success

    You would always be programming for failure:

    x.doSomething()

    if (!x.doSomething()) return false;

    Error Handling (Contd)

  • 8/3/2019 2 Exception Handling1

    5/29

    Throwing Exceptions

    Exceptions: Can't be overlooked

    Sent directly to an exception handlernot just caller offailed method

    Throw an exception object to signal anexceptional condition

    Example: IllegalArgumentException:

    Continued

    illegal parameter value

    IllegalArgumentException exception

    = new IllegalArgumentException("Amount exceeds balance");

    throw exception;

  • 8/3/2019 2 Exception Handling1

    6/29

    Throwing Exceptions (Contd)

    No need to store exception object in avariable:

    When an exception is thrown, methodterminates immediately

    Execution continues with an exception handler

    throw new IllegalArgumentException("Amount exceeds balance");

  • 8/3/2019 2 Exception Handling1

    7/29

    Exception Handling: An Example

    public class BankAccount {

    public void withdraw(double amount) {

    if (amount > balance) {

    IllegalArgumentException exception

    = new IllegalArgumentException("Amountexceeds balance");

    throw exception;

    }

    balance = balance - amount;

    }

    . . .

    }

  • 8/3/2019 2 Exception Handling1

    8/29

    Hierarchy of Exception Classes

    Figure 1: The Hierarchy of Exception Classes

  • 8/3/2019 2 Exception Handling1

    9/29

    Hierarchy of Exception Classes (Contd)

    Figure 2: The Hierarchy of Exception Classes

  • 8/3/2019 2 Exception Handling1

    10/29

    Hierarchy of Exception Classes (Contd)

    Figure 3: The Hierarchy of Exception Classes

  • 8/3/2019 2 Exception Handling1

    11/29

    Hierarchy of Exception Classes (Contd)

    Figure 4: The Hierarchy of Exception Classes

  • 8/3/2019 2 Exception Handling1

    12/29

    Syntax: Throwing an Exception

    throw exceptionObject;

    Example:throw new IllegalArgumentException();

    Purpose:

    To throw an exception and transfer control to a handler for thisexception type

  • 8/3/2019 2 Exception Handling1

    13/29

    The Exception Class

    Simple: only

    constructor

    methods.

    Figure 5: The Exception Class

  • 8/3/2019 2 Exception Handling1

    14/29

    Handling Exceptions

    When an exception occurs, an object will throw an exception. Theexception handler, possibly the same object, will catch it.

    Figure 6: Flow of Handling Exceptions

  • 8/3/2019 2 Exception Handling1

    15/29

    Example: Two Classes

    Throw in one class...

    Catch in the other.

    Figure 7: Flow of Handling Exceptions

  • 8/3/2019 2 Exception Handling1

    16/29

    Checked and Unchecked Exceptions

    Two types of exceptions:

    Checked:

    The compiler checks that you don't ignore them

    Due to external circumstances that theprogrammer cannot prevent

    Majority occur when dealing with input and output

    For example, IOException

  • 8/3/2019 2 Exception Handling1

    17/29

    Checked and Unchecked Exceptions (Contd)

    Two types of exceptions: Unchecked:

    Extend the class RuntimeException or Error

    They are the programmer's fault

    Examples of runtime exceptions:

    Example of error: OutOfMemoryError

    NumberFormatException

    IllegalArgumentException

    NullPointerException

  • 8/3/2019 2 Exception Handling1

    18/29

    Categories aren't perfect:

    Scanner.nextInt throws uncheckedInputMismatchException

    Programmer cannot prevent users from enteringincorrect input

    This choice makes the class easy to use for beginningprogrammers

    Deal with checked exceptions principallywhen programming with files and streams

    Checked and Unchecked Exceptions (Contd)

  • 8/3/2019 2 Exception Handling1

    19/29

    For example, use a Scanner to read a file

    But, FileReader constructor can throw aFileNotFoundException

    String filename = . . .;

    FileReader reader = new FileReader(filename);

    Scanner in = new Scanner(reader);

    Checked and Unchecked Exceptions (Contd)

  • 8/3/2019 2 Exception Handling1

    20/29

    Two choices:

    Handle the exception

    Tell compiler that you want method to be terminated

    when the exception occurs Use throws specifier so method can throw a

    checked exception

    public void read(String filename) throws FileNotFoundException {

    FileReader reader = new FileReader(filename);

    Scanner in = new Scanner(reader);

    . . .

    }

    Checked and Unchecked Exceptions (Contd)

  • 8/3/2019 2 Exception Handling1

    21/29

    For multiple exceptions:

    Keep in mind inheritance hierarchy:If method can throw an IOException andFileNotFoundException, only use IOException

    Better to declare exception than to handle it

    incompetently

    public void read(String filename)

    throws IOException, ClassNotFoundException

    Checked and Unchecked Exceptions (Contd)

  • 8/3/2019 2 Exception Handling1

    22/29

    An Example: NumberFormatException

    When expecting integer inputs, if the user types a

    non-integer number, then an exception of typeNumberFormatException is thrown!

  • 8/3/2019 2 Exception Handling1

    23/29

    Syntax: Exception Specification

    accessSpecifier returnType

    methodName(parameterType parameterName, . . .)

    throws ExceptionClass, ExceptionClass, . . .

    Example:public void read(BufferedReader in) throws IOException

    Purpose:To indicate the checked exceptions that this method can throw

  • 8/3/2019 2 Exception Handling1

    24/29

    Catching Exceptions

    Install an exception handler with try/catch

    statement

    tryblock contains statements that may

    cause an exception

    catch clause contains handler for an

    exception type

  • 8/3/2019 2 Exception Handling1

    25/29

    Catching Exceptions (Contd)

    Example:

    try {

    String filename = . . .;

    FileReader reader = new FileReader(filename);

    Scanner in = new Scanner(reader);String input = in.next();

    int value = Integer.parseInt(input);

    . . .

    }

    catch (IOException exception) {

    exception.printStackTrace();}

    catch (NumberFormatException exception) {

    System.out.println("Input was not a number");

    }

  • 8/3/2019 2 Exception Handling1

    26/29

    Statements in try block are executed

    If no exceptions occur, catch clauses are

    skipped

    If exception of matching type occurs,executionjumps to catch clause

    If exception of another type occurs, it isthrown until it is caught by another try

    blockContinued

    Catching Exceptions (Contd)

  • 8/3/2019 2 Exception Handling1

    27/29

    catch (IOException exception) block

    exception contains reference to the exception

    object that was thrown

    catch clause can analyze object to find out moredetails

    exception.printStackTrace(): printout of

    chain of method calls that lead to exception

    Catching Exceptions (Contd)

  • 8/3/2019 2 Exception Handling1

    28/29

    Syntax: General Try Block

    try {statement

    statement. . .

    }catch (ExceptionClass exceptionObject) {statement

    statement. . .

    }catch (ExceptionClass exceptionObject) {

    statementstatement. . .

    }. . .

  • 8/3/2019 2 Exception Handling1

    29/29

    Syntax: General Try Block (Contd)

    Example:try {

    System.out.println("How old are you?");

    int age = in.nextInt();

    System.out.println("Next year, you'll be " + (age + 1));}

    catch (InputMismatchException exception) {

    exception.printStackTrace();

    }

    Purpose:To execute one or more statements that may generate exceptions. If an exceptionoccurs and it matches one of the catch clauses, execute the first one that matches.If no exception occurs, or an exception is thrown that doesn't match any catchclause, then skip the catch clauses.