Chapter 14 – Exception Handling

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Advertisements

Topics Introduction Types of Errors Exceptions Exception Handling
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Exception Handling. Introduction Errors can be dealt with at place error occurs –Easy to see if proper error checking implemented –Harder to read application.
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Outline DivideByZeroTes t.java 1 // Fig. 15.1: DivideByZeroTest.java 2 // An exception-handling example that checks for divide-by-zero. 3 import java.awt.*;
 2003 Prentice Hall, Inc. All rights reserved. Chapter 15 – Exception Handling Outline 15.1 Introduction 15.2 Exception-Handling Overview 15.3 Exception-Handling.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
 2005 Pearson Education, Inc. All rights reserved Exception Handling.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Objectives Understanding what an exception is Understanding the heirarchy of exception classes Learn the types of exception and how to catch and handle.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Exception Handling Recitation – 10/(23,24)/2008 CS 180 Department of Computer Science, Purdue University.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other Error Handling Techniques 14.4The Basics.
 2002 Prentice Hall. All rights reserved. 1 Exception Handling Overview Exception handling –Enable clear, robust and more fault-tolerant programs –Process.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming: Guided Learning with Early Objects
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
Exceptions and Assertions Chapter 15 – CSCI 1302.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
Exception Handling Outline 23.1 Introduction
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 4 – Completing the Inventory Application.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 5.1 Test-Driving the Enhanced Inventory Application.
OOP (Java): Exceptions/ OOP Objectives – –examine Java's exception handling Semester 2, Exceptions.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Appendix H Exception Handling: A Deeper Look
Java Exceptions a quick review….
IS 0020 Program Design and Software Tools
Exceptions: When things go wrong
Chapter 10 – Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Why exception handling in C++?
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
COMPSCI 230 S Programming Techniques
Exception Handling Chapter 9.
ATS Application Programming: Java Programming
Abdulmotaleb El Saddik University of Ottawa
Exception Handling and Reading / Writing Files
Exception Handling Chapter 9 Edited by JJ.
Fundamental Error Handling
Web Design & Development Lecture 7
Lecture 11 Objectives Learn what an exception is.
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Java Basics Exception Handling.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 15 – Exception Handling
Presentation transcript:

Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3 Other Error-Handling Techniques 14.4 Basics of Java Exception Handling 14.5 try Blocks 14.6 Throwing an Exception 14.7 Catching an Exception 14.8 Exception-Handling Example: Divide by Zero 14.9 Rethrowing an Exception 14.10 throws Clause 14.11 Constructors, Finalizers and Exception Handling 14.12 Exceptions and Inheritance 14.13 finally Block 14.14 Using printStackTrace and getMessage

14.1 Introduction Exception handling Exception Handles errors Indication of problem during execution E.g., array out of bounds Handles errors Class Exception

14.2 When Exception Handling Should Be Used Uses of exception handling When method cannot complete its task Process exceptions from program components Handle exceptions in a uniform manner in large projects

14.3 Other Error-Handling Techniques Using no error-handling Not for mission critical applications Exit application on error Program must return resources

14.4 Basics of Java Exception Handling A method detects an error and throws an exception Exception handler processes the error The error is considered caught and handled in this model Code that could generate errors put in try blocks Code for error handling enclosed in a catch block The finally always executes with or without an error Keyword throws tells exceptions of a method Termination model of exception handling The block in which the exception occurs expires

14.5 try Blocks The try block structure try { statements that may throw an exception } catch ( ExceptionType exceptionReference ) { statements to process an exception } A try followed by any number of catch blocks

Subclasses of Throwable 14.6 Throwing an Exception The throw statement Indicates an exception has occurred Operand any class derived from Throwable Subclasses of Throwable Class Exception Problems that should be caught Class Error Serious exception should not be caught Control moves from try block to catch block

Handler catches exception 14.7 Catching an Exception Handler catches exception Executes code in catch block Should only catch Exceptions Program terminates if no appropriate handler Single catch can handle multiple exceptions Many ways to write exception handlers

14.8 Exception-Handling Example: Divide by Zero Common programming mistake Throws ArithmeticException

DivideByZeroException.java Lines 8-11 Lines 14-17 1 // Fig. 14.1: DivideByZeroException.java 2 // Definition of class DivideByZeroException. 3 // Used to throw an exception when a 4 // divide-by-zero is attempted. 5 public class DivideByZeroException extends ArithmeticException { 6 7 // no-argument constructor specifies default error message 8 public DivideByZeroException() 9 { 10 super( "Attempted to divide by zero" ); 11 } 12 13 // constructor to allow customized error message 14 public DivideByZeroException( String message ) 15 { 16 super( message ); 17 } 18 19 } // end class DivideByZeroException DivideByZeroException.java Lines 8-11 Lines 14-17 Specify String as exception message (indicates error) Alternate constructor specifies String as exception message

DivideByZeroTest.java Lines 21-51 1 // Fig. 14.2: DivideByZeroTest.java 2 // A simple exception handling example. 3 // Checking for a divide-by-zero-error. 4 5 // Java core packages 6 import java.awt.*; 7 import java.awt.event.*; 8 import java.text.DecimalFormat; 9 10 // Java extension packages 11 import javax.swing.*; 12 13 public class DivideByZeroTest extends JFrame 14 implements ActionListener { 15 16 private JTextField inputField1, inputField2, outputField; 17 private int number1, number2; 18 private double result; 19 20 // set up GUI 21 public DivideByZeroTest() 22 { 23 super( "Demonstrating Exceptions" ); 24 25 // get content pane and set its layout 26 Container container = getContentPane(); 27 container.setLayout( new GridLayout( 3, 2 ) ); 28 29 // set up label and inputField1 30 container.add( 31 new JLabel( "Enter numerator ", SwingConstants.RIGHT ) ); 32 inputField1 = new JTextField( 10 ); 33 container.add( inputField1 ); 34 DivideByZeroTest.java Lines 21-51 Constructor builds graphical user interface and registers DivideByZeroTest

DivideByZeroTest.java Lines 54-84 Lines 61-67 Lines 62-63 Line 65 35 // set up label and inputField2; register listener 36 container.add( 37 new JLabel( "Enter denominator and press Enter ", 38 SwingConstants.RIGHT ) ); 39 inputField2 = new JTextField( 10 ); 40 container.add( inputField2 ); 41 inputField2.addActionListener( this ); 42 43 // set up label and outputField 44 container.add( 45 new JLabel( "RESULT ", SwingConstants.RIGHT ) ); 46 outputField = new JTextField(); 47 container.add( outputField ); 48 49 setSize( 425, 100 ); 50 setVisible( true ); 51 } 52 53 // process GUI events 54 public void actionPerformed( ActionEvent event ) 55 { 56 DecimalFormat precision3 = new DecimalFormat( "0.000" ); 57 58 outputField.setText( "" ); // clear outputField 59 60 // read two numbers and calculate quotient 61 try { 62 number1 = Integer.parseInt( inputField1.getText() ); 63 number2 = Integer.parseInt( inputField2.getText() ); 64 65 result = quotient( number1, number2 ); 66 outputField.setText( precision3.format( result ) ); 67 } 68 DivideByZeroTest.java Lines 54-84 Lines 61-67 Lines 62-63 Line 65 Method actionPerformed called when after input entered The try block Read integers from JTextFields Method quotient attempts division

DivideByZeroTest.java Lines 70-75 Lines 78-83 Lines 88-95 69 // process improperly formatted input 70 catch ( NumberFormatException numberFormatException ) { 71 JOptionPane.showMessageDialog( this, 72 "You must enter two integers", 73 "Invalid Number Format", 74 JOptionPane.ERROR_MESSAGE ); 75 } 76 77 // process attempts to divide by zero 78 catch ( ArithmeticException arithmeticException ) { 79 JOptionPane.showMessageDialog( this, 80 arithmeticException.toString(), 81 "Arithmetic Exception", 82 JOptionPane.ERROR_MESSAGE ); 83 } 84 } 85 86 // method quotient demonstrated throwing an exception 87 // when a divide-by-zero error occurs 88 public double quotient( int numerator, int denominator ) 89 throws DivideByZeroException 90 { 91 if ( denominator == 0 ) 92 throw new DivideByZeroException(); 93 94 return ( double ) numerator / denominator; 95 } 96 Catch NumberFormatException DivideByZeroTest.java Lines 70-75 Lines 78-83 Lines 88-95 Catch DivideByZeroException Method quotient divides two integers

DivideByZeroTest.java Program Output 97 // execute application 98 public static void main( String args[] ) 99 { 100 DivideByZeroTest application = new DivideByZeroTest(); 101 102 application.setDefaultCloseOperation( 103 JFrame.EXIT_ON_CLOSE ); 104 } 105 106 } // end class DivideByZeroTest DivideByZeroTest.java Program Output

14.9 Rethrowing an Exception Rethrow exception if catch cannot handle it

RuntimeExceptions occur during execution 14.10 throws Clause Lists the exceptions thrown by a method int functionName( paramterList ) throws ExceptionType1, ExceptionType2,… { // method body } RuntimeExceptions occur during execution ArrayIndexOutOfBoundsException NullPointerException Declare exceptions a method throws

14.11 Constructors, Finalizers, and Exception Handling Throw exception if constructor causes error Finalize called when object garbage collected

14.12 Exceptions and Inheritance Inheritance of exception classes Allows polymorphic processing of related exceptions

14.13 finally Block Resource leak The finally block Caused when resources are not released by a program The finally block Appears after catch blocks Always executes Use to release resources

UsingExceptions.java Lines 7-21 Line 11 Lines 15-18 Line 20 Line 29 1 // Fig. 14.9: UsingExceptions.java 2 // Demonstration of the try-catch-finally 3 // exception handling mechanism. 4 public class UsingExceptions { 5 6 // execute application 7 public static void main( String args[] ) 8 { 9 // call method throwException 10 try { 11 throwException(); 12 } 13 14 // catch Exceptions thrown by method throwException 15 catch ( Exception exception ) 16 { 17 System.err.println( "Exception handled in main" ); 18 } 19 20 doesNotThrowException(); 21 } 22 23 // demonstrate try/catch/finally 24 public static void throwException() throws Exception 25 { 26 // throw an exception and immediately catch it 27 try { 28 System.out.println( "Method throwException" ); 29 throw new Exception(); // generate exception 30 } 31 UsingExceptions.java Lines 7-21 Line 11 Lines 15-18 Line 20 Line 29 Method main immediately enters try block Calls method throwException Handle exception thrown by throwException Call method doesNotThrow-Exception Method throws new Exception

UsingExceptions.java Line 33 Line 37 Lines 44-47 Lines 61-64 32 // catch exception thrown in try block 33 catch ( Exception exception ) 34 { 35 System.err.println( 36 "Exception handled in method throwException" ); 37 throw exception; // rethrow for further processing 38 39 // any code here would not be reached 40 } 41 42 // this block executes regardless of what occurs in 43 // try/catch 44 finally { 45 System.err.println( 46 "Finally executed in throwException" ); 47 } 48 49 // any code here would not be reached 50 } 51 52 // demonstrate finally when no exception occurs 53 public static void doesNotThrowException() 54 { 55 // try block does not throw an exception 56 try { 57 System.out.println( "Method doesNotThrowException" ); 58 } 59 60 // catch does not execute, because no exception thrown 61 catch( Exception exception ) 62 { 63 System.err.println( exception.toString() ); 64 } 65 Catch Exception UsingExceptions.java Line 33 Line 37 Lines 44-47 Lines 61-64 Rethrow Exception The finally block executes, even though Exception thrown Skip catch block since no Exception thrown

UsingExceptions.java Lines 68-71 Program Output 66 // this block executes regardless of what occurs in 67 // try/catch 68 finally { 69 System.err.println( 70 "Finally executed in doesNotThrowException" ); 71 } 72 73 System.out.println( 74 "End of method doesNotThrowException" ); 75 } 76 77 } // end class UsingExceptions UsingExceptions.java Lines 68-71 Program Output The finally block always executes Method throwException Exception handled in method throwException Finally executed in throwException Exception handled in main Method doesNotThrowException Finally executed in doesNotThrowException End of method doesNotThrowException !

UsingExceptions.java Line 10 Line 14 1 // Fig. 14.10: UsingExceptions.java 2 // Demonstration of stack unwinding. 3 public class UsingExceptions { 4 5 // execute application 6 public static void main( String args[] ) 7 { 8 // call throwException to demonstrate stack unwinding 9 try { 10 throwException(); 11 } 12 13 // catch exception thrown in throwException 14 catch ( Exception exception ) { 15 System.err.println( "Exception handled in main" ); 16 } 17 } 18 UsingExceptions.java Line 10 Line 14 Call method throwException Catch Exception from method throwExcetion

UsingExceptions.java Lines 21-39 Line 30 Program Output 19 // throwException throws an exception that is not caught in 20 // the body of this method 21 public static void throwException() throws Exception 22 { 23 // throw an exception and catch it in main 24 try { 25 System.out.println( "Method throwException" ); 26 throw new Exception(); // generate exception 27 } 28 29 // catch is incorrect type, so Exception not caught 30 catch( RuntimeException runtimeException ) { 31 System.err.println( 32 "Exception handled in method throwException" ); 33 } 34 35 // finally block always executes 36 finally { 37 System.err.println( "Finally is always executed" ); 38 } 39 } 40 41 } // end class UsingExceptions Method throwException UsingExceptions.java Lines 21-39 Line 30 Program Output Cannot catch RuntimeException so catch in main Method throwException Finally is always executed Exception handled in main

14.14 Using printStackTrace and getMessage Method printStackTrace Prints the method call stack Throwable class Method getMessage retrieves informationString

UsingExceptions.java Lines 16-17 1 // Fig. 14.11: UsingExceptions.java 2 // Demonstrating the getMessage and printStackTrace 3 // methods inherited into all exception classes. 4 public class UsingExceptions { 5 6 // execute application 7 public static void main( String args[] ) 8 { 9 // call method1 10 try { 11 method1(); 12 } 13 14 // catch Exceptions thrown from method1 15 catch ( Exception exception ) { 16 System.err.println( exception.getMessage() + "\n" ); 17 exception.printStackTrace(); 18 } 19 } 20 21 // call method2; throw exceptions back to main 22 public static void method1() throws Exception 23 { 24 method2(); 25 } 26 27 // call method3; throw exceptions back to method1 28 public static void method2() throws Exception 29 { 30 method3(); 31 } 32 UsingExceptions.java Lines 16-17 Error information generated by getMessage and printStackTrace

UsingExceptions.java Line 36 Program Output 33 // throw Exception back to method2 34 public static void method3() throws Exception 35 { 36 throw new Exception( "Exception thrown in method3" ); 37 } 38 39 } // end class Using Exceptions UsingExceptions.java Line 36 Program Output Throw an Exception that propagates back to main Exception thrown in method3   java.lang.Exception: Exception thrown in method3 at UsingExceptions.method3(UsingExceptions.java:36) at UsingExceptions.method2(UsingExceptions.java:30) at UsingExceptions.method1(UsingExceptions.java:24) at UsingExceptions.main(UsingExceptions.java:11))