Presentation is loading. Please wait.

Presentation is loading. Please wait.

DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exception Handling.

Similar presentations


Presentation on theme: "DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exception Handling."— Presentation transcript:

1 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exception Handling

2 DCS 2133 Object Oriented Programming Objectives To understand the concept of exception handling when program execution errors occur. To implement exception handling in program execution.

3 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction A program can be written assuming that nothing unusual or incorrect will happen. –The user will always enter an integer when prompted to do so. –There will always be a nonempty list for a program that takes an entry from the list. –The file containing the needed information will always exist. Unfortunately, it isn’t always so.

4 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction Once the core program is written for the usual, expected case(s), Java’s exception-handling facilities should be added to accommodate the unusual, unexpected case(s). Exception handling divides a class or method definition into separate sections: –one section for the normal case(s) –another section for the exceptional case(s). Depending on how a method is used, special cases may need to be handled in different ways.

5 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exception What is exception? An error condition that can occur during the normal course of program execution. Exception handling – resolving exceptions that may occur so program can continue or terminate gracefully Exception handling enables programmers to create programs that are more robust and fault- tolerant.

6 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exception handling When an exception occurs, or is thrown, the normal sequence of flow is terminated. The exception-handling routine is then executed; we say the thrown exception is caught.

7 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Example of No Catching Exceptions String inputStr; int age; inputStr = JOptionPane.showInputDialog(null, "Age:"); age = Integer.parseInt(inputStr); java.lang.NumberFormatException: ten at java.lang.Integer.parseInt(Integer.java:405) at java.lang.Integer.parseInt(Integer.java:454) at Ch8Sample1.main(Ch8Sample1.java:20) Error message for invalid input

8 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions in Java: Example Simple example –Suppose the students are hosting an event to express appreciation to their lecturer, at which donuts and milk will be served. –If the number of donuts is known, and the number of glasses of milk is known, it should be possible to calculate the number of donuts per class of milk.

9 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions in Java: Example, cont. Simple example, cont. –But what if there is no milk because the cows are on strike? –An attempt to divide the number of donuts by the number of glasses of milk will result in an attempt to divide by zero. –This would be an complete disaster, known in Java as an exception.

10 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions in Java: Example, cont. In Java, it is possible to test for this unusual situation using an if-else statement, for example. class GotMilk

11 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions in Java: Example, cont.

12 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions in Java: Example, cont. In Java, it is also possible to throw an exception. class ExceptionDemo

13 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions in Java: Example, cont.

14 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions in Java: Example, cont.

15 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions in Java Exceptions are handled using a try-throw-catch threesome. try block syntax try { Code_to_Try Throw_An_Exception_Or_Invoke_A_Method _That_Might_Throw_An_Exception Possibly_More_Code } try { Code_to_Try Throw_An_Exception_Or_Invoke_A_Method _That_Might_Throw_An_Exception Possibly_More_Code }

16 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions in Java try block – encloses code that might throw an exception and the code that should not execute if an exception occurs Consists of keyword try followed by a block of code enclosed in curly braces

17 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Catching Exceptions catch block – catches (i.e., receives) and handles an exception, contains: –Begins with keyword catch –Exception parameter in parentheses – exception parameter identifies the exception type and enables catch block to interact with caught exception object –Block of code in curly braces that executes when exception of proper type occurs

18 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Catching an exception using try – catch block inputStr = JOptionPane.showInputDialog(null, "Age:"); try { age = Integer.parseInt(inputStr); } catch (NumberFormatException e){ JOptionPane.showMessageDialog(null, "’" + inputStr + "‘ is invalid\n" + "Please enter digits only"); } trycatch

19 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Remaining statements in the try block is skipped. try {... } catch (Exception e) {... } try-catch Control Flow Assume throws an exception. Assume throws an exception. Exception Statements in the catch block are executed. And the execution continues to the next statement try {... } catch (Exception e) {... } No Exception Statements in the catch block are skipped. All statements in the try block are executed.

20 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Using try-catch statement in a loop while (true){ inputStr = JOptionPane.showInputDialog(null, "Age:"); try { age = Integer.parseInt(inputStr); return age; } catch (NumberFormatException e){ JOptionPane.showMessageDialog(null, "’" + inputStr + "‘ is invalid\n" + "Please enter digits only"); } trycatch

21 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Another Example – Divide by Zero Exception public static int quotient( int numerator, int denominator ) { return numerator / denominator; // possible division by zero } public static void main( String args[] ) { Scanner scanner = new Scanner( System.in ); System.out.print( "Please enter an integer numerator: " ); int numerator = scanner.nextInt(); System.out.print( "Please enter an integer denominator: " ); int denominator = scanner.nextInt(); int result = quotient( numerator, denominator ); System.out.printf( "\nResult: %d / %d = %d\n", numerator, denominator, result ); }

22 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Getting Information There are two methods we can call to get information about the thrown exception: –getMessage –printStackTrace try {... } catch (NumberFormatException e){ System.out.println(e.getMessage()); System.out.println(e.printStackTrace()); } ten java.lang.NumberFormatException: ten at java.lang.Integer.parseInt.... getMessage printStacktrace

23 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Multiple catch Blocks A single try-catch statement can include multiple catch blocks, one for each type of exception. try {... age = Integer.parseInt(inputStr);... val = cal.get(id); //cal is a GregorianCalendar... } catch (NumberFormatException e){... } catch (ArrayIndexOutOfBoundsException e){... }

24 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. All catch blocks are skipped. try {... }... } No Exception Multiple catch Control Flow All statements in the try block are executed and throw no exceptions. Remaining statements in the try block is skipped. try {... }... } Assume throws an exception and is the matching block. Assume throws an exception and is the matching block. Exception Statements in the matching catch block are executed.

25 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. The finally Block There are situations where we need to take certain actions regardless of whether an exception is thrown or not. We place statements that must be executed regardless of exceptions in the finally block.

26 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. try-catch-finally Control Flow No Exception try {...... }...... } finally {... } Assume throws an exception and is the matching block. Assume throws an exception and is the matching block. Exception try {...... }...... } finally {... } finally block is executed.

27 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Propagating Exceptions Instead of catching a thrown exception by using the try- catch statement, we can propagate the thrown exception back to the caller of our method. The method header includes the reserved word throws. public int getAge( ) throws NumberFormatException {... int age = Integer.parseInt(inputStr);... return age; }

28 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Throwing Exceptions We can write a method that throws an exception directly, i.e., this method is the origin of the exception. Use the throw reserved to create a new instance of the Exception or its subclasses. The method header includes the reserved word throws. public void doWork(int num) throws Exception {... if (num != val) throw new Exception("Invalid val");... }

29 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exception Thrower When a method may throw an exception, either directly or indirectly, we call the method an exception thrower. Every exception thrower must be one of two types: –catcher. –propagator.

30 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Types of Exception Throwers An exception catcher is an exception thrower that includes a matching catch block for the thrown exception. An exception propagator does not contain a matching catch block. A method may be a catcher of one exception and a propagator of another.

31 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Sample Call Sequence try { B(); } catch (Exception e){... } Method A try { C(); } catch (Exception e){... } Method B try { D(); } catch (Exception e){... Method C if (cond) { throw new Exception(); Method D propagator catcher AA B A B C A B C D Stack Trace

32 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exception Types All types of thrown errors are instances of the Throwable class or its subclasses. Serious errors are represented by instances of the Error class or its subclasses. Exceptional cases that common applications should handle are represented by instances of the Exception class or its subclasses.

33 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Throwable Hierarchy There are over 60 classes in the hierarchy.

34 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Checked vs. Runtime There are two types of exceptions: –Checked. –Unchecked. A checked exception is an exception that is checked at compile time. All other exceptions are unchecked, or runtime, exceptions. As the name suggests, they are detected only at runtime.

35 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Different Handling Rules When calling a method that can throw checked exceptions –use the try-catch statement and place the call in the try block, or –modify the method header to include the appropriate throws clause. When calling a method that can throw runtime exceptions, it is optional to use the try-catch statement or modify the method header to include a throws clause.

36 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Handling Checked Exceptions

37 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Handling Runtime Exceptions

38 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Programmer-Defined Exceptions Using the standard exception classes, we can use the getMessage method to retrieve the error message. By defining our own exception class, we can pack more useful information –for example, we may define a OutOfStock exception class and include information such as how many items to order AgeInputException is defined as a subclass of Exception and includes public methods to access three pieces of information it carries: lower and upper bounds of valid age input and the (invalid) value entered by the user.

39 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Example – AgeInputException class AgeInputException extends Exception { private static final String DEFAULT_MESSAGE = "Input out of bounds"; private int lowerBound; private int upperBound; private int value; public AgeInputException(int low, int high, int input) { this(DEFAULT_MESSAGE, low, high, input); } public AgeInputException(String msg, int low, int high, int input) { super(msg); if (low > high) { throw new IllegalArgumentException(); } lowerBound = low; upperBound = high; value = input; } class AgeInputException extends Exception { private static final String DEFAULT_MESSAGE = "Input out of bounds"; private int lowerBound; private int upperBound; private int value; public AgeInputException(int low, int high, int input) { this(DEFAULT_MESSAGE, low, high, input); } public AgeInputException(String msg, int low, int high, int input) { super(msg); if (low > high) { throw new IllegalArgumentException(); } lowerBound = low; upperBound = high; value = input; } public int lowerBound() { return lowerBound; } public int upperBound() { return upperBound; } public int value() { return value; } public int lowerBound() { return lowerBound; } public int upperBound() { return upperBound; } public int value() { return value; }

40 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Example – AgeInputVer5 import javax.swing.*; class AgeInputVer5 { private static final String DEFAULT_MESSAGE = "Your age:"; private static final int DEFAULT_LOWER_BOUND = 0; private static final int DEFAULT_UPPER_BOUND = 99; private int lowerBound; private int upperBound; public AgeInputVer5( ) throws IllegalArgumentException { setBounds(DEFAULT_LOWER_BOUND, DEFAULT_UPPER_BOUND); } public AgeInputVer5(int low, int high) throws IllegalArgumentException { if (low > high) { throw new IllegalArgumentException( "Low (" + low + ") was " + "larger than high(" + high + ")"); } else { setBounds(low, high); } public int getAge() throws AgeInputException { return getAge(DEFAULT_MESSAGE); } import javax.swing.*; class AgeInputVer5 { private static final String DEFAULT_MESSAGE = "Your age:"; private static final int DEFAULT_LOWER_BOUND = 0; private static final int DEFAULT_UPPER_BOUND = 99; private int lowerBound; private int upperBound; public AgeInputVer5( ) throws IllegalArgumentException { setBounds(DEFAULT_LOWER_BOUND, DEFAULT_UPPER_BOUND); } public AgeInputVer5(int low, int high) throws IllegalArgumentException { if (low > high) { throw new IllegalArgumentException( "Low (" + low + ") was " + "larger than high(" + high + ")"); } else { setBounds(low, high); } public int getAge() throws AgeInputException { return getAge(DEFAULT_MESSAGE); } public int getAge(String prompt) throws AgeInputException { String inputStr; int age; while (true) { inputStr = JOptionPane.showInputDialog(null, prompt); try { age = Integer.parseInt(inputStr); if (age upperBound) { throw new AgeInputException("Input out of bound", lowerBound, upperBound, age); } return age; //input okay so return the value & exit } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "'" + inputStr + "' is invalid\n“ + "Please enter digits only"); } private void setBounds(int low, int high) { lowerBound = low; upperBound = high; } public int getAge(String prompt) throws AgeInputException { String inputStr; int age; while (true) { inputStr = JOptionPane.showInputDialog(null, prompt); try { age = Integer.parseInt(inputStr); if (age upperBound) { throw new AgeInputException("Input out of bound", lowerBound, upperBound, age); } return age; //input okay so return the value & exit } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "'" + inputStr + "' is invalid\n“ + "Please enter digits only"); } private void setBounds(int low, int high) { lowerBound = low; upperBound = high; }

41 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Example -AgeInputExceptionDemo import javax.swing.*; class Ch8TestAgeInputVer5 { public static void main( String[] args ) { int entrantAge; try { AgeInputVer5 input = new AgeInputVer5(25, 50); entrantAge = input.getAge("Your Age:"); //continue the processing JOptionPane.showMessageDialog(null, "Input Okay"); //TEMP } catch (AgeInputException e) { JOptionPane.showMessageDialog(null, "Error: " + e.value() + " is entered. It is " + "outside the valid range of [" + e.lowerBound() + ", " + e.upperBound() + "]"); } import javax.swing.*; class Ch8TestAgeInputVer5 { public static void main( String[] args ) { int entrantAge; try { AgeInputVer5 input = new AgeInputVer5(25, 50); entrantAge = input.getAge("Your Age:"); //continue the processing JOptionPane.showMessageDialog(null, "Input Okay"); //TEMP } catch (AgeInputException e) { JOptionPane.showMessageDialog(null, "Error: " + e.value() + " is entered. It is " + "outside the valid range of [" + e.lowerBound() + ", " + e.upperBound() + "]"); }

42 DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Sample output Enter 0 Will produce


Download ppt "DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exception Handling."

Similar presentations


Ads by Google