06 exceptions_java 02

Upload: mhoa43

Post on 02-Jun-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/10/2019 06 Exceptions_JAVA 02

    1/24

    17/1

    Exceptions

    Reading: Savitch, Chapter 8

  • 8/10/2019 06 Exceptions_JAVA 02

    2/24

    17/2

    Objectives

    To learn how to handle an exception(exception propagation).To learn how to define an exception.

  • 8/10/2019 06 Exceptions_JAVA 02

    3/24

    17/3

    Exception Propagation

    If it is not appropriate to handle theexception where it occurs, it can be handledat a higher level.Exceptions can be propagated up throughthe method calling hierarchy until they are

    caught and handled or until they reach theoutermost level (the main() method).

  • 8/10/2019 06 Exceptions_JAVA 02

    4/24

    17/4

    Example

    //Propagation_Demo.java

    public class Propagation_Demo {

    public static void main (String [ ] args) {System.out.println("program beginning");Exception_Scope demo =

    new Exception_Scope();demo.level_1(); // method callSystem.out.println("program ending");

    }}

  • 8/10/2019 06 Exceptions_JAVA 02

    5/24

    17/5

    // Exception_Scope.java defines three methods// level_3, level_2, level_1

    class Exception_Scope {public void level_3 (int adjustment) {

    System.out.println("level_3 beginning");int current = 1;current = current /adjustment;

    // dont handle exceptions here

    System.out.println("level_3 ending");}

  • 8/10/2019 06 Exceptions_JAVA 02

    6/24

    17/6

    public void level_2 () {

    System.out.println("level_2 beginning");level_3(0);

    // dont handle exceptions here System.out.println("level_2 ending");

    }

  • 8/10/2019 06 Exceptions_JAVA 02

    7/2417/7

    //Exceptions are handled in the method

    // when it calls a methodpublic void level_1 () {

    System.out.println("level_1 beginning");try {

    level_2();}catch (ArithmeticException problem) {

    System.out.println(problem.getMessage());

    problem.printStackTrace();}

    } // end of level_1} // end of class

  • 8/10/2019 06 Exceptions_JAVA 02

    8/2417/8

    The program execution

    % jav a Pro p ag at io n _Dem o program beginning

    level_1 beginninglevel_2 beginninglevel_3 beginning

  • 8/10/2019 06 Exceptions_JAVA 02

    9/2417/9

    / by zero

    java.lang.ArithmeticException: / by zeroat Exception_Scope.level_3(Propagation_Demo.java:16)at Exception_Scope.level_2(Propagation_Demo.java:21)at Exception_Scope.level_1(Propagation_Demo.java:28)

    at Propagation_Demo.main(Propagation_Demo.java:7) program ending

  • 8/10/2019 06 Exceptions_JAVA 02

    10/2417/10

    User Defined Exceptions

    A programmer can define their ownexception class by extending the class from

    an existing API exception class.

  • 8/10/2019 06 Exceptions_JAVA 02

    11/2417/11

    Exceptions are thrown using the throw statement.

    The syntax of the statement is

    When you use a throw-statement in yourcode you should usually define your ownexception class.

    If you use a predefined, more generalexception class, then your catch-block willhave to be general

    t row exceptionObject;

  • 8/10/2019 06 Exceptions_JAVA 02

    12/24

    17/12

    Example//Throw_Demo.java

    import java.io.IOException;public class Throw_Demo {public static void main(String[] args) throws Ooops {

    Ooops problem = new Ooops(Alert!);

    throw problem;}

    }

    class Ooops extends IOException {Ooops(String message) { super(message); }

    }

  • 8/10/2019 06 Exceptions_JAVA 02

    13/24

    17/13

    The program execution is

    % java Throw_ emoException in thread "main" Ooops: Alert!

    at java.lang.Throwable.fillInStackTrace(Native Method)at java.lang.Throwable.(Throwable.java:94)at java.lang.Exception.(Exception.java:42)at java.io.IOException.(IOException.java:47)at Ooops.(Throw_Demo.java:12)at Throw_Demo.main(Throw_Demo.java:7)

  • 8/10/2019 06 Exceptions_JAVA 02

    14/24

    17/14

    Usually a throw statement is nested insidean if statement that evaluates the conditionto see if the exception should be thrown.

  • 8/10/2019 06 Exceptions_JAVA 02

    15/24

    17/15

    Example//ThrowEx.java

    import java.io.*;

    public class ThrowEx {public static void main(String [ ] args) throws IOException{

    try {

    System.out.println("Your current age is " + getAge());}

  • 8/10/2019 06 Exceptions_JAVA 02

    16/24

    17/16

    catch(NumberTooBigException e1){

    System.out.println(e1.getMessage());}

    catch(NumberTooSmallException e2)

    {System.out.println(Invalid input. Try again.");

    }} // end of main

  • 8/10/2019 06 Exceptions_JAVA 02

    17/24

    17/17

    static int getAge() throws IOException,NumberTooBigException,NumberTooSmallException

    {

    BufferedReader stdin = new BufferedReader(new InputStreamReader (System.in));

    System.out.print ("Enter your age: ");int age = Integer.parseInt (stdin.readLine());

  • 8/10/2019 06 Exceptions_JAVA 02

    18/24

    17/18

    if (age > 130)

    throw new NumberTooBigException("Are you sure you are that old?");

    else if (age < 0)throw new NumberTooSmallException();

    elsereturn age;

    } // end of getAge} // end of ThrowEx class

  • 8/10/2019 06 Exceptions_JAVA 02

    19/24

    17/19

    class NumberTooBigException extends Exception{

    public NumberTooBigException (){ super(); }public NumberTooBigException (String s){ super(s); }

    }

  • 8/10/2019 06 Exceptions_JAVA 02

    20/24

    17/20

    class NumberTooSmallException extends Exception{

    public NumberTooSmallException() {super();}public NumberTooSmallException (String s) {super(s); }

    }

  • 8/10/2019 06 Exceptions_JAVA 02

    21/24

    17/21

    The program executions

    % jav a Th ro w ExEnter your age: 80

    Your current age is 80

  • 8/10/2019 06 Exceptions_JAVA 02

    22/24

    17/22

    % jav a Th ro w ExEnter your age: -4Invalid input. Try again.

    % jav a Th ro w ExEnter your age: 140

    Are you sure you are that old?

  • 8/10/2019 06 Exceptions_JAVA 02

    23/24

    17/23

    SummaryAn exception is an object descended from the Exception

    classYou can use predefined exception classes or define your ownExceptions can be thrown by: certain Java statements

    methods from class libraries explicit use of the throw statement

    An exception can be thrown in either a try block, or a method definition without a try block, but in this case

    the call to the method must be placed inside a try block

  • 8/10/2019 06 Exceptions_JAVA 02

    24/24

    17/24

    SummaryAn exception is caught in a catch block

    When a method might throw an exception but does not have acatch block to catch it, usually the exception class must belisted in the throws -clause for the methodA try block may be followed by more than one catch block more than one catch block may be capable of handling the

    exception the first catch block that can handle the exception is the only

    one that executes so put the most specific catch blocks first and the most

    general lastEvery exception class has a getMessage method to retrieve atext message description of the exception caught