 2003 Prentice Hall, Inc. All rights reserved. Chapter 15 – Exception Handling Outline 15.1 Introduction 15.2 Exception-Handling Overview 15.3 Exception-Handling.

Slides:



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

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 Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
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.*;
Java Exception Very slightly modified from K.P. Chow University of Hong Kong (some slides from S.M. Yiu)
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
 Pearson Education, Inc. All rights reserved Exception Handling.
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.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
E XCEPTION H ANDLING Chapter 11 C S 442: A DVANCED J AVA P ROGRAMMING.
 2005 Pearson Education, Inc. All rights reserved Exception Handling.
Objectives Understanding what an exception is Understanding the heirarchy of exception classes Learn the types of exception and how to catch and handle.
1 Nested Classes O. 2 Possible to declare a class within another class; called nested classes Nested class should have some specific association with.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
 2002 Prentice Hall. All rights reserved Exception-Handling Overview Exception handling –improves program clarity and modifiability by removing.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Java Software Solutions Foundations of Program Design Sixth Edition
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.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: Exception Handling
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Slides Credit Umair Javed LUMS Web Application Development.
Java Programming: Guided Learning with Early Objects
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
1 Advanced Flow of Control : Introduction This chapter focuses on: –exception processing –catching and handling exceptions –creating new exceptions –exception.
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.
Unit 4 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
 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 in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
© 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.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Appendix H Exception Handling: A Deeper Look
Chapter 14 – Exception Handling
Chapter 10 – Exception Handling
ATS Application Programming: Java Programming
Exceptions Exception handling is an important aspect of object-oriented design Chapter 10 focuses on the purpose of exceptions exception messages the.
Abdulmotaleb El Saddik University of Ottawa
Web Design & Development Lecture 7
Lecture 11 Objectives Learn what an exception is.
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 15 – Exception Handling
Presentation transcript:

 2003 Prentice Hall, Inc. All rights reserved. Chapter 15 – Exception Handling Outline 15.1 Introduction 15.2 Exception-Handling Overview 15.3 Exception-Handling Example: Divide by Zero 15.4 Java Exception Hierarchy 15.5 Rethrowing an Exception 15.6 finally Clause 15.7 Stack Unwinding 15.8 printStackTrace, getStackTrace and getMessage 15.9 Chained Exceptions Declaring New Exception Types Constructors and Exception Handling

 2003 Prentice Hall, Inc. All rights reserved Introduction Exception handling –Exception Indication of problem during execution –E.g., divide by zero –Chained exceptions

 2003 Prentice Hall, Inc. All rights reserved Exception-Handling Overview Uses of exception handling –Process exceptions from program components –Handle exceptions in a uniform manner in large projects –Remove error-handling code from “main line” of execution A method detects an error and throws an exception –Exception handler processes the error –Uncaught exceptions yield adverse effects Might terminate program execution

 2003 Prentice Hall, Inc. All rights reserved Exception-Handling Overview Code that could generate errors put in try blocks –Code for error handling enclosed in a catch clause –The finally clause always executes Termination model of exception handling –The block in which the exception occurs expires throws clause specifies exceptions method throws

 2003 Prentice Hall, Inc. All rights reserved Exception-Handling Example: Divide by Zero Common programming mistake Throws ArithmeticException

 2003 Prentice Hall, Inc. All rights reserved. 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.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class DivideByZeroTest extends JFrame 8 implements ActionListener { 9 10 private JTextField inputField1, inputField2, outputField; 11 private int number1, number2, result; // set up GUI 14 public DivideByZeroTest() 15 { 16 super( "Demonstrating Exceptions" ); // get content pane and set its layout 19 Container container = getContentPane(); 20 container.setLayout( new GridLayout( 3, 2 ) ); // set up label and inputField1 23 container.add( 24 new JLabel( "Enter numerator ", SwingConstants.RIGHT ) ); 25 inputField1 = new JTextField(); 26 container.add( inputField1 );

 2003 Prentice Hall, Inc. All rights reserved. Outline DivideByZeroTes t.java Line 51 Lines // set up label and inputField2; register listener 29 container.add( new JLabel( "Enter denominator and press Enter ", 30 SwingConstants.RIGHT ) ); 31 inputField2 = new JTextField(); 32 container.add( inputField2 ); 33 inputField2.addActionListener( this ); // set up label and outputField 36 container.add( new JLabel( "RESULT ", SwingConstants.RIGHT ) ); 37 outputField = new JTextField(); 38 container.add( outputField ); setSize( 425, 100 ); 41 setVisible( true ); } // end DivideByZeroTest constructor // process GUI events 46 public void actionPerformed( ActionEvent event ) 47 { 48 outputField.setText( "" ); // clear outputField // read two numbers and calculate quotient 51 try { 52 number1 = Integer.parseInt( inputField1.getText() ); 53 number2 = Integer.parseInt( inputField2.getText() ); The try blockRead integers from JTextField s

 2003 Prentice Hall, Inc. All rights reserved. Outline DivideByZeroTes t.java Line 55 Line 60 Line 67 Line result = quotient( number1, number2 ); 56 outputField.setText( String.valueOf( result ) ); 57 } // process improperly formatted input 60 catch ( NumberFormatException numberFormatException ) { 61 JOptionPane.showMessageDialog( this, 62 "You must enter two integers", "Invalid Number Format", 63 JOptionPane.ERROR_MESSAGE ); 64 } // process attempts to divide by zero 67 catch ( ArithmeticException arithmeticException ) { 68 JOptionPane.showMessageDialog( this, 69 arithmeticException.toString(), "Arithmetic Exception", 70 JOptionPane.ERROR_MESSAGE ); 71 } } // end method actionPerformed // demonstrates throwing an exception when a divide-by-zero occurs 76 public int quotient( int numerator, int denominator ) 77 throws ArithmeticException 78 { 79 return numerator / denominator; 80 } Method quotient attempts division Catch NumberFormatException Catch ArithmeticException Method quotient throws ArithmeticException

 2003 Prentice Hall, Inc. All rights reserved. Outline DivideByZeroTes t.java public static void main( String args[] ) 83 { 84 DivideByZeroTest application = new DivideByZeroTest(); 85 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 86 } } // end class DivideByZeroTest

 2003 Prentice Hall, Inc. All rights reserved Java Exception Hierarchy Superclass Throwable –Subclass Exception Exceptional situations Should be caught by program –Subclass Error Typically not caught by program Checked exceptions –Catch or declare Unchecked exceptions

 2003 Prentice Hall, Inc. All rights reserved. Fig. 15.2Inheritance hierarchy for class Throwable Throwable ExceptionError AWTErrorThreadDeathIOExceptionRuntimeExceptionOutOfMemoryError

 2003 Prentice Hall, Inc. All rights reserved Rethrowing an Exception Rethrow exception if catch cannot handle it

 2003 Prentice Hall, Inc. All rights reserved finally Clause Resource leak –Caused when resources are not released by a program The finally block –Appears after catch blocks –Always executes –Use to release resources

 2003 Prentice Hall, Inc. All rights reserved. Outline UsingExceptions.java 1 // Fig. 15.3: UsingExceptions.java 2 // Demonstration of the try-catch-finally exception handling mechanism. 3 public class UsingExceptions { 4 5 public static void main( String args[] ) 6 { 7 try { 8 throwException(); // call method throwException 9 } // catch Exceptions thrown by method throwException 12 catch ( Exception exception ) { 13 System.err.println( "Exception handled in main" ); 14 } doesNotThrowException(); 17 } // demonstrate try/catch/finally 20 public static void throwException() throws Exception 21 { 22 // throw an exception and immediately catch it 23 try { 24 System.out.println( "Method throwException" ); 25 throw new Exception(); // generate exception 26 }

 2003 Prentice Hall, Inc. All rights reserved. Outline UsingExceptions.java Line 32 Lines // catch exception thrown in try block 29 catch ( Exception exception ) { 30 System.err.println( 31 "Exception handled in method throwException" ); 32 throw exception; // rethrow for further processing // any code here would not be reached 35 } // this block executes regardless of what occurs in try/catch 38 finally { 39 System.err.println( "Finally executed in throwException" ); 40 } // any code here would not be reached } // end method throwException // demonstrate finally when no exception occurs 47 public static void doesNotThrowException() 48 { 49 // try block does not throw an exception 50 try { 51 System.out.println( "Method doesNotThrowException" ); 52 } The finally block executes, even though Exception thrown Rethrow Exception

 2003 Prentice Hall, Inc. All rights reserved. Outline 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 Lines // catch does not execute, because no exception thrown 55 catch ( Exception exception ) { 56 System.err.println( exception ); 57 } // this clause executes regardless of what occurs in try/catch 60 finally { 61 System.err.println( 62 "Finally executed in doesNotThrowException" ); 63 } System.out.println( "End of method doesNotThrowException" ); } // end method doesNotThrowException } // end class UsingExceptions The finally block always executes

 2003 Prentice Hall, Inc. All rights reserved Stack Unwinding Exception not caught in scope –Method terminates –Stack unwinding occurs –Another attempt to catch exception

 2003 Prentice Hall, Inc. All rights reserved. Outline UsingExceptions.java Line 9 Line 13 Line 19 Line 24 1 // Fig. 15.4: UsingExceptions.java 2 // Demonstration of stack unwinding. 3 public class UsingExceptions { 4 5 public static void main( String args[] ) 6 { 7 // call throwException to demonstrate stack unwinding 8 try { 9 throwException(); 10 } // catch exception thrown in throwException 13 catch ( Exception exception ) { 14 System.err.println( "Exception handled in main" ); 15 } 16 } // throwException throws exception that is not caught in this method 19 public static void throwException() throws Exception 20 { 21 // throw an exception and catch it in main 22 try { 23 System.out.println( "Method throwException" ); 24 throw new Exception(); // generate exception 25 } 26 Call method throwException Catch Exception from method throwExcetion Method declares a throws clause Throw an Exception

 2003 Prentice Hall, Inc. All rights reserved. Outline UsingExceptions.java 27 // catch is incorrect type, so Exception is not caught 28 catch ( RuntimeException runtimeException ) { 29 System.err.println( 30 "Exception handled in method throwException" ); 31 } // finally clause always executes 34 finally { 35 System.err.println( "Finally is always executed" ); 36 } } // end method throwException } // end class UsingExceptions Method throwException Finally is always executed Exception handled in main

 2003 Prentice Hall, Inc. All rights reserved printStackTrace, getStackTrace and getMessage Throwable class –Method printStackTrace Prints method call stack –Method getStackTrace Obtains stack-trace information –Method getMessage Returns descriptive string

 2003 Prentice Hall, Inc. All rights reserved. Outline UsingExceptions.java Line 8 Lines Lines // Fig. 15.5: UsingExceptions.java 2 // Demonstrating getMessage and printStackTrace from class Exception. 3 public class UsingExceptions { 4 5 public static void main( String args[] ) 6 { 7 try { 8 method1(); // call method1 9 } // catch Exceptions thrown from method1 12 catch ( Exception exception ) { 13 System.err.println( exception.getMessage() + "\n" ); 14 exception.printStackTrace(); // obtain the stack-trace information 17 StackTraceElement[] traceElements = exception.getStackTrace(); System.out.println( "\nStack trace from getStackTrace:" ); 20 System.out.println( "Class\t\tFile\t\t\tLine\tMethod" ); // loop through traceElements to get exception description 23 for ( int i = 0; i < traceElements.length; i++ ) { 24 StackTraceElement currentElement = traceElements[ i ]; 25 System.out.print( currentElement.getClassName() + "\t" ); 26 System.out.print( currentElement.getFileName() + "\t" ); Print information generated by getMessage and printStackTrace Call method1 Print StackTraceElement s

 2003 Prentice Hall, Inc. All rights reserved. Outline UsingExceptions.java Lines Line 37 Line 39 Line 43 Line 45 Line 49 Line System.out.print( currentElement.getLineNumber() + "\t" ); 28 System.out.print( currentElement.getMethodName() + "\n" ); } // end for statement } // end catch } // end method main // call method2; throw exceptions back to main 37 public static void method1() throws Exception 38 { 39 method2(); 40 } // call method3; throw exceptions back to method1 43 public static void method2() throws Exception 44 { 45 method3(); 46 } // throw Exception back to method2 49 public static void method3() throws Exception 50 { 51 throw new Exception( "Exception thrown in method3" ); 52 } Throw an Exception that propagates back to main method1 declares a throw clause Call method2method2 declares a throw clause Call method3method3 declares a throw clause Print StackTraceElement s

 2003 Prentice Hall, Inc. All rights reserved. Outline UsingExceptions.java } // end class Using Exceptions Exception thrown in method3 java.lang.Exception: Exception thrown in method3 at UsingExceptions.method3(UsingExceptions.java:51) at UsingExceptions.method2(UsingExceptions.java:45) at UsingExceptions.method1(UsingExceptions.java:39) at UsingExceptions.main(UsingExceptions.java:8) Stack trace from getStackTrace: Class File Line Method UsingExceptions UsingExceptions.java 51 method3 UsingExceptions UsingExceptions.java 45 method2 UsingExceptions UsingExceptions.java 39 method1 UsingExceptions UsingExceptions.java 8 main

 2003 Prentice Hall, Inc. All rights reserved Chained Exceptions Wraps existing exception in a new exception –enables exception to maintain complete stack-trace

 2003 Prentice Hall, Inc. All rights reserved. Outline UsingChainedExc eptions.java Line 8 Lines Line 18 Line 21 Line 26 1 // Fig. 15.6: UsingChainedExceptions.java 2 // Demonstrating chained exceptions. 3 public class UsingChainedExceptions { 4 5 public static void main( String args[] ) 6 { 7 try { 8 method1(); // call method1 9 } // catch Exceptions thrown from method1 12 catch ( Exception exception ) { 13 exception.printStackTrace(); 14 } 15 } // call method2; throw exceptions back to main 18 public static void method1() throws Exception 19 { 20 try { 21 method2(); // call method2 22 } // catch Exception thrown from method2 25 catch ( Exception exception ) { 26 throw new Exception( "Exception thrown in method1", exception ); Call method1 Catch Exception and print stack trace method1 declares a throw clause Call method2 An existing Exception is chained to another

 2003 Prentice Hall, Inc. All rights reserved. Outline UsingChainedExc eptions.java Line 31 Line 34 Line 39 Line } 28 } // call method3; throw exceptions back to method1 31 public static void method2() throws Exception 32 { 33 try { 34 method3(); // call method3 35 } // catch Exception thrown from method3 38 catch ( Exception exception ) { 39 throw new Exception( "Exception thrown in method2", exception ); 40 } 41 } // throw Exception back to method2 44 public static void method3() throws Exception 45 { 46 throw new Exception( "Exception thrown in method3" ); 47 } } // end class Using Exceptions An existing Exception is chained to another method2 declares a throw clause Call method3 Throw a new Exception

 2003 Prentice Hall, Inc. All rights reserved. Outline UsingChainedExc eptions.java java.lang.Exception: Exception thrown in method1 at UsingChainedExceptions.method1(UsingChainedExceptions.java:26) at UsingChainedExceptions.main(UsingChainedExceptions.java:8) Caused by: java.lang.Exception: Exception thrown in method2 at UsingChainedExceptions.method2(UsingChainedExceptions.java:39) at UsingChainedExceptions.method1(UsingChainedExceptions.java:21)... 1 more Caused by: java.lang.Exception: Exception thrown in method3 at UsingChainedExceptions.method3(UsingChainedExceptions.java:46) at UsingChainedExceptions.method2(UsingChainedExceptions.java:34)... 2 more

 2003 Prentice Hall, Inc. All rights reserved Declaring New Exception Types Extend existing exception class

 2003 Prentice Hall, Inc. All rights reserved Constructors and Exception Handling Throw exception if constructor causes error