 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.

Slides:



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

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Topics Introduction Types of Errors Exceptions Exception Handling
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
Exception Handling. Introduction Errors can be dealt with at place error occurs –Easy to see if proper error checking implemented –Harder to read application.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS102--Object Oriented Programming
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.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 23 - Exception Handling Outline 23.1Introduction 23.2When Exception Handling Should Be Used 23.3Other.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
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:
Dale Roberts Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
For use of Cleveland State's IST410 Students only 1 Exception.
 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.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions CIS 304 Intermediate Java Programming for Business.
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
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.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 13 - Exception Handling Outline 13.1Introduction 13.2When Exception Handling Should Be Used.
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.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
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.
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.
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.
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 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 23 - Exception Handling Outline 23.1Introduction.
Exception Handling Outline 23.1 Introduction
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.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Chapter 14 – Exception Handling
Chapter 10 – Exception Handling
Why exception handling in C++?
Part IX Fundamentals of C and C++ Programming Exception Handling
Abdulmotaleb El Saddik University of Ottawa
Web Design & Development Lecture 7
Lecture 11 Objectives Learn what an exception is.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Department of Computer and Information Science, School of Science, IUPUI Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI
Java Basics Exception Handling.
CMSC 202 Exceptions.
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 15 – Exception Handling
Presentation transcript:

 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other Error Handling Techniques 14.4The Basics of Java Exception Handling 14.5An Exception Handling Example: Divide by Zero 14.6Try Blocks 14.7Throwing an Exception 14.8Catching an Exception 14.9Rethrowing an Exception 14.10Throws Clause 14.11Constructors, Finalizers and Exception Handling 14.12Exceptions and Inheritance finally Block 14.14Using printStackTrace and getMessage

 2000 Prentice Hall, Inc. All rights reserved Introduction Errors can be dealt with at place error occurs –Easy to see if proper error checking implemented –Harder to read application itself and see how code works Exception handling –Makes clear, robust, fault-tolerant programs –Java removes error handling code from "main line" of program Common failures –Out of bounds array subscript –Division by zero –Null pointer exception

 2000 Prentice Hall, Inc. All rights reserved Introduction Exception handling –Catch errors before they occur –Used when system can recover from error Exception handler - recovery procedure Error dealt with in different place than where it occurred –Useful when program cannot recover but must shut down cleanly

 2000 Prentice Hall, Inc. All rights reserved When Exception Handling Should Be Used Error handling used for –Processing exceptional situations –Processing exceptions for components that cannot handle them directly –Large projects that require uniform error processing

 2000 Prentice Hall, Inc. All rights reserved Other Error Handling Techniques Other techniques –Ignore exceptions Personal programs usually ignore errors Not for commercial software –Abort Fine for most programs Inappropriate for mission critical programs

 2000 Prentice Hall, Inc. All rights reserved The Basics of Java Exception Handling Exception handling –Method detects error it cannot deal with Throws an exception –Exception handler Code to catch exception and handle it –Exception only caught if handler exists If exception not caught, block terminates

 2000 Prentice Hall, Inc. All rights reserved The Basics of Java Exception Handling Format –Enclose code that may have an error in try block –Follow with one or more catch blocks Each catch block has an exception handler –If exception occurs and matches parameter in catch block Code in catch block executed –If no exception thrown Exception handling code skipped Control resumes after catch blocks try{ code that may throw exceptions } catch (ExceptionType ref) { exception handling code }

 2000 Prentice Hall, Inc. All rights reserved The Basics of Java Exception Handling Termination model of exception handling –throw point Place where exception occurred Control cannot return to throw point –Block which threw exception expires –Possible to give information to exception handler

 2000 Prentice Hall, Inc. All rights reserved An Exception Handling Example: Divide by Zero Example program –User enters two integers to be divided –We want to catch division by zero errors –Exceptions Objects derived from class Exception –Look in Exception classes in java.lang Nothing appropriate for divide by zero Closest is ArithmeticException Extend and create our own exception class

 2000 Prentice Hall, Inc. All rights reserved An Exception Handling Example: Divide by Zero –Two constructors for most exception classes One with no arguments (default), with default message One that receives exception message Call to superclass constructor –Code that may throw exception in try block Covered in more detail in following sections –Error handling code in catch block –If no exception thrown, catch blocks skipped 5public class DivideByZeroException 6 extends ArithmeticException { 7 public DivideByZeroException() 12 public DivideByZeroException( String message )

 2000 Prentice Hall, Inc. All rights reserved. Outline Class DivideByZero Exception ( extends Arithmetic Exception ) 1.2 Constructors 1.3 super 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 5public class DivideByZeroException 6 extends ArithmeticException { 7 public DivideByZeroException() 8 { 9 super( "Attempted to divide by zero" ); 10 } public DivideByZeroException( String message ) 13 { 14 super( message ); 15 } 16} 17 Define our own exception class (exceptions are thrown objects). Default constructor (default message) and customizable message constructor.

 2000 Prentice Hall, Inc. All rights reserved. Outline Set up GUI 18// Fig. 14.1: DivideByZeroTest.java 19// A simple exception handling example. 20// Checking for a divide-by-zero-error. 21import java.text.DecimalFormat; 22import javax.swing.*; 23import java.awt.*; 24import java.awt.event.*; 25 26public class DivideByZeroTest extends JFrame 27 implements ActionListener { 28 private JTextField input1, input2, output; 29 private int number1, number2; 30 private double result; // Initialization 33 public DivideByZeroTest() 34 { 35 super( "Demonstrating Exceptions" ); Container c = getContentPane(); 38 c.setLayout( new GridLayout( 3, 2 ) ); c.add( new JLabel( "Enter numerator ", 41 SwingConstants.RIGHT ) ); 42 input1 = new JTextField( 10 ); 43 c.add( input1 ); c.add( 46 new JLabel( "Enter denominator and press Enter ", 47 SwingConstants.RIGHT ) );

 2000 Prentice Hall, Inc. All rights reserved. Outline Process GUI events 2.1 try block 48 input2 = new JTextField( 10 );49 c.add( input2 ); 50 input2.addActionListener( this ); c.add( new JLabel( "RESULT ", SwingConstants.RIGHT ) ); 55 output = new JTextField(); 56 c.add( output ); setSize( 425, 100 ); 59 show(); 60 } // Process GUI events 63 public void actionPerformed( ActionEvent e ) 64 { 65 DecimalFormat precision3 = new DecimalFormat( "0.000" ); output.setText( "" ); // empty the output JTextField try { 70 number1 = Integer.parseInt( input1.getText() ); 71 number2 = Integer.parseInt( input2.getText() ); result = quotient( number1, number2 ); 74 output.setText( precision3.format( result ) ); 75 } Notice enclosing try block. If an exception is thrown in the block (even from a method call), the entire block is terminated.

 2000 Prentice Hall, Inc. All rights reserved. Outline catch blocks 3. quotient 4. main catch ( NumberFormatException nfe ) { 77 JOptionPane.showMessageDialog( this, 78 "You must enter two integers", 79 "Invalid Number Format", 80 JOptionPane.ERROR_MESSAGE ); 81 } 82 catch ( DivideByZeroException dbze ) { 83 JOptionPane.showMessageDialog( this, dbze.toString(), 84 "Attempted to Divide by Zero", 85 JOptionPane.ERROR_MESSAGE ); 86 } 87 } // Definition of method quotient. Used to demonstrate 90 // throwing an exception when a divide-by-zero error 91 // is encountered. 92 public double quotient( int numerator, int denominator ) 93 throws DivideByZeroException 94 { if ( denominator == 0 ) 96 throw new DivideByZeroException(); return ( double ) numerator / denominator; 99 } public static void main( String args[] ) 102 { 103 DivideByZeroTest app = new DivideByZeroTest(); catch blocks have error handling code. Control resumes after the catch blocks. The first block makes sure the inputs are of the correct type. Method quotient throws an DivideByZeroException exception (object) if denominator == 0.

 2000 Prentice Hall, Inc. All rights reserved. Outline 15 Program Output 106 app.addWindowListener( 107 new WindowAdapter() { 108 public void windowClosing( WindowEvent e ) 109 { 110 e.getWindow().dispose(); 111 System.exit( 0 ); 112 } 113 } 114 ); 115 } 116}

 2000 Prentice Hall, Inc. All rights reserved. Outline 16 Program Output

 2000 Prentice Hall, Inc. All rights reserved Try Blocks Exceptions that occurs in a try block –Usually caught by handler specified by following catch block Can have any number of catch blocks –If no exceptions thrown, catch blocks skipped try{ code that may throw exceptions } catch ( ExceptionType ref ) { exception handling code }

 2000 Prentice Hall, Inc. All rights reserved Throwing an Exception throw –Indicates exception has occurred (throwing an exception) –Operand Object of any class derived from Throwable –Derived from Throwable: When exception thrown –Control exits current try block –Proceeds to catch handler (if exists) 95 if ( denominator == 0 ) 96 throw new DivideByZeroException();

 2000 Prentice Hall, Inc. All rights reserved Throwing an Exception Exceptions –Can still throw exceptions without explicit throw statement –ArrayIndexOutOfBoundsException –Terminates block that threw exception Not required to terminate program

 2000 Prentice Hall, Inc. All rights reserved Catching an Exception catch blocks –Contain exception handlers –Format: –To catch all exceptions, catch an exception object: catch( Exception e ) catch( ExceptionType ref ) { error handling code } 82 catch ( DivideByZeroException dbze ) { 83 JOptionPane.showMessageDialog( this, dbze.toString(), 84 "Attempted to Divide by Zero", 85 JOptionPane.ERROR_MESSAGE ); 86 }

 2000 Prentice Hall, Inc. All rights reserved Catching an Exception Catching exceptions –First handler to catch exception does All other handlers skipped –If exception not caught Searches enclosing try blocks for appropriate handler –If still not caught, non-GUI based applications terminate try{ try{ throw Exception2 } catch ( Exception1 ){...} } catch( Exception2 ){...}

 2000 Prentice Hall, Inc. All rights reserved Rethrowing an Exception Rethrowing exceptions –Use if handler cannot process exception –Rethrow exception with the statement: throw e; Detected by next enclosing try block –Handler can always rethrow exception, even if it performed some processing

 2000 Prentice Hall, Inc. All rights reserved Throws Clause Run-time exceptions –Derive from RunTimeException –Some exceptions can occur at any point ArrayIndexOutOfBoundsException NullPointerException –Create object reference without attaching object to reference ClassCastException –Invalid casts –Most avoidable by writing proper code

 2000 Prentice Hall, Inc. All rights reserved Throws Clause Checked exceptions –Must be listed in throws clause of method –All non- RuntimeException s Unchecked exceptions –Can be thrown from almost any method Tedious to write throws clause every time No throws clause needed

 2000 Prentice Hall, Inc. All rights reserved Throws Clause Catch-or-declare requirement –If method calls another method that explicitly throws checked exceptions Exceptions must be in original method's throws clause –Otherwise, original method must catch exception –Method must either catch exception or declare it in the throw clause –Figures contain lists of exceptions

 2000 Prentice Hall, Inc. All rights reserved finally Block finally block –Placed after last catch block –Always executed, regardless whether exceptions thrown or caught –If exception thrown in finally block, processed by enclosing try block

 2000 Prentice Hall, Inc. All rights reserved. Outline main 1.1 throwException 1.2 catch 2. Define throwException 2.1 try 2.2 catch 2.3 finally 1// Fig. 14.9: UsingExceptions.java 2// Demonstration of stack unwinding. 3public class UsingExceptions { 4 public static void main( String args[] ) 5 { 6 try { 7 7 throwException(); 8 } 9 catch ( Exception e ) { 10 System.err.println( "Exception handled in main" ); 11 } 12 } public static void throwException() throws Exception 15 { 16 // Throw an exception and catch it in main. 17 try { 18 System.out.println( "Method throwException" ); throw new Exception(); // generate exception 20 } 21 catch( RuntimeException e ) { // nothing caught here 22 System.out.println( "Exception handled in " + 23 "method throwException" ); 24 } 25 finally { 26 System.err.println( "Finally is always executed" ); 27 } 28 } 29} Call method throwException (enclosed in a try block). Throw an Exception. The catch block cannot handle it, but the finally block executes irregardless.

 2000 Prentice Hall, Inc. All rights reserved. Outline 28 Program Output Method throwException Finally is always executed Exception handled in main

 2000 Prentice Hall, Inc. All rights reserved Using printStackTrace and getMessage Class Throwable –Superclass of all exceptions –Method printStackTrace Prints method call stack for caught Exception object –Most recent method on top of stack Helpful for testing/debugging –Constructors Exception() Exception( String informationString ) –informationString may be accessed with method getMessage

 2000 Prentice Hall, Inc. All rights reserved. Outline main 1.1 try 1.2 getMessage 1.3 printStackTrace 2. method1 3. method2 4. method3 4.1 throw 1// Fig : UsingExceptions.java 2// Demonstrating the getMessage and printStackTrace 3// methods inherited into all exception classes. 4public class UsingExceptions { 5 public static void main( String args[] ) 6 { 7 try { 8 8 method1(); 9 } 10 catch ( Exception e ) { System.err.println( e.getMessage() + "\n" ); e.printStackTrace(); 14 } 15 } public static void method1() throws Exception 18 { 19 method2(); 20 } public static void method2() throws Exception 23 { 24 method3(); 25 } public static void method3() throws Exception 28 { 29 throw new Exception( "Exception thrown in method3" ); 30 } 31} Call method1, which calls method2, which calls method3, which throws an exception. getMessage prints the String the Exception was initialized with. printStackTrace prints the methods in this order: method3 method2 method1 main (order they were called when exception occurred)

 2000 Prentice Hall, Inc. All rights reserved. Outline 31 Program Output Exception thrown in method3 java.lang.Exception: Exception thrown in method3 at UsingExceptions.method3(UsingExceptions.java:28) at UsingExceptions.method2(UsingExceptions.java:23) at UsingExceptions.method1(UsingExceptions.java:18) at UsingExceptions.main(UsingExceptions.java:8)