Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Topics Introduction Types of Errors Exceptions Exception Handling
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
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)
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
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.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 15 – Exception Handling Outline 15.1 Introduction 15.2 Exception-Handling Overview 15.3 Exception-Handling.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
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 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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
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.
 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. Lecture Objectives To learn how to throw exceptions To be able to design your own exception classes To understand the difference between.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java 212: Exceptions Handling. Chapter Objectives Learn what an exception is See how a try / catch block is used to handle exceptions Become aware of.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Exception Handling Recitation – 10/(23,24)/2008 CS 180 Department of Computer Science, Purdue University.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
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.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
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.
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.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Java Programming: Guided Learning with Early Objects
COMP Exception Handling Yi Hong June 10, 2015.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
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.
 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.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
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.
Chapter 14 – Exception Handling
Chapter 10 – Exception Handling
Chapter 14: Exception Handling
Exception Handling Chapter 9.
Exception Handling Chapter 9 Edited by JJ.
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.
Chapter 12 Exception Handling and Text IO Part 1
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 15 – Exception Handling
Presentation transcript:

Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth Edition Fourth Edition

Java Programming: From Problem Analysis to Program Design, Second Edition2 Objectives  Learn what an exception is.  See how a try / catch block is used to handle exceptions.  Become aware of the hierarchy of exception classes.  Learn about checked and unchecked exceptions.  Learn how to handle exceptions within a program.  Discover how to throw and rethrow an exception.  Learn how to handle events in a program.

Java Programming: From Problem Analysis to Program Design, Second Edition3 Exception  An occurrence of an undesirable situation that can be detected during program execution.  Examples:  Division by zero.  Trying to open an input file that does not exist.  An array index that goes out of bounds.

Java Programming: From Problem Analysis to Program Design, Second Edition4 Handling Exceptions within a Program  Can use an if statement to handle an exception.  However, suppose that division by zero occurs in more than one place within the same block.  In this case, using if statements may not be the most effective way to handle the exception.

Java Programming: From Problem Analysis to Program Design, Second Edition5 Java’s Mechanism of Exception Handling  When an exception occurs, an object of a particular exception class is created.  Java provides a number of exception classes to effectively handle certain common exceptions, such as:  Division by zero  Invalid input  File not found

Java Programming: From Problem Analysis to Program Design, Second Edition6 Java’s Mechanism of Exception Handling  Division by zero is:  An arithmetic error.  Handled by the class ArithmeticException.  When a division by zero exception occurs, the program creates an object of the class ArithmeticException.

Java Programming: From Problem Analysis to Program Design, Second Edition7 Java’s Mechanism of Exception Handling  When a Scanner object is used to input data into a program, any invalid input errors are handled using the class InputMismatchException.  The class Exception (directly or indirectly) is the superclass of all the exception classes in Java.

Java Programming: From Problem Analysis to Program Design, Second Edition8 try / catch / finally Block  Statements that might generate an exception are placed in a try block.  The try block:  Might also contain statements that should not be executed if an exception occurs.  Is followed by zero or more catch blocks.  A catch block:  Specifies the type of exception it can catch.  Contains an exception handler.

Java Programming: From Problem Analysis to Program Design, Second Edition9 try / catch / finally Block  The last catch block may or may not be followed by a finally block.  Any code contained in a finally block always executes regardless of whether an exception occurs, except when the program exits early from a try block by calling the method System.exit.  If a try block has no catch block, then it must have the finally block.

Java Programming: From Problem Analysis to Program Design, Second Edition10 try / catch / finally Block

Java Programming: From Problem Analysis to Program Design, Second Edition11 try / catch / finally Block  If no exception is thrown in a try block, all catch blocks associated with the try block are ignored and program execution resumes after the last catch block.  If an exception is thrown in a try block, the remaining statements in the try block are ignored.  The program searches the catch blocks in the order in which they appear after the try block and looks for an appropriate exception handler.

Java Programming: From Problem Analysis to Program Design, Second Edition12 try / catch / finally Block  If the type of the thrown exception matches the parameter type in one of the catch blocks, the code of that catch block executes and the remaining catch blocks are ignored.  If there is a finally block after the last catch block, the finally block executes regardless of whether an exception occurs.

Java Programming: From Problem Analysis to Program Design, Second Edition13 Order of catch Blocks  The heading of a catch block specifies the type of exception it handles.  A catch block can catch either all exceptions of a specific type or all types of exceptions.  A reference variable of a superclass type can point to an object of its subclass.

Java Programming: From Problem Analysis to Program Design, Second Edition14 Order of catch Blocks  If you declare an exception using the class Exception in the heading of a catch block, then that catch block can catch all types of exceptions because the class Exception is the superclass of all exception classes.  In a sequence of catch blocks following a try block, a catch block that declares an exception of a subclass type should be placed before catch blocks that declare exceptions of a superclass type.

Java Programming: From Problem Analysis to Program Design, Second Edition15 Order of catch Blocks

Java Programming: From Problem Analysis to Program Design, Second Edition16 Order of catch Blocks

Java Programming: From Problem Analysis to Program Design, Second Edition17 Order of catch Blocks

Java Programming: From Problem Analysis to Program Design, Second Edition18 Order of catch Blocks

Java Programming: From Problem Analysis to Program Design, Second Edition19 Order of catch Blocks

Java Programming: From Problem Analysis to Program Design, Second Edition20 Java’s Exception Class  class Exception :  Subclass of class Throwable.  Superclass of classes designed to handle exceptions.  Various types of exceptions:  I/O exceptions.  Number format exceptions.  File not found exceptions.  Array index out of bounds exceptions.  Various exceptions categorized into separate classes and contained in various packages.

Java Programming: From Problem Analysis to Program Design, Second Edition21 Java’s Exception Class

Java Programming: From Problem Analysis to Program Design, Second Edition22 Java’s Exception Class

Java Programming: From Problem Analysis to Program Design, Second Edition23 Java’s Exception Class

Java Programming: From Problem Analysis to Program Design, Second Edition24 Java’s Exception Class

Java Programming: From Problem Analysis to Program Design, Second Edition25 Java’s Exception Class

Java Programming: From Problem Analysis to Program Design, Second Edition26 Java’s Exception Class

Java Programming: From Problem Analysis to Program Design, Second Edition27 Checked Exceptions  Any exception that can be analyzed by the compiler.  Example:  FileNotFoundExceptions.

Java Programming: From Problem Analysis to Program Design, Second Edition28 Unchecked Exceptions  Exceptions that cannot be analyzed when the program compiles (must be checked for by programmer).  Examples:  Division by zero  Array index out of bounds  Syntax: throws ExceptionType1, ExceptionType2,... ExceptionType1, ExceptionType2, and so on are names of exception classes

Java Programming: From Problem Analysis to Program Design, Second Edition29 Exceptions Example Code public static void exceptionMethod() throws InputMismatchException, FileNotFoundException { //statements }  The method exceptionMethod throws exceptions of the type InputMismatchException and FileNotFoundException.

Java Programming: From Problem Analysis to Program Design, Second Edition30 The class Exception and the Operator instanceof  A reference of a superclass type can point to objects of its subclass.  You can determine if a reference variable points to an object using the operator instanceof.  You can combine catch blocks using this facility.

Java Programming: From Problem Analysis to Program Design, Second Edition31 try { System.out.print("Line 4: Enter the " + "dividend: "); dividend = console.nextInt(); System.out.println(); System.out.print("Line 7: Enter the " + "divisor: "); divisor = console.nextInt(); System.out.println(); quotient = dividend / divisor; System.out.println("Line 11: Quotient = " + quotient); } catch (Exception eRef) { if (eRef instanceof ArithmeticException) System.out.println("Line 14: Exception " + eRef.toString()); else if (eRef instanceof InputMismatchException) System.out.println("Line 16: Exception " + eRef.toString()); } The class Exception and the Operator instanceof

Java Programming: From Problem Analysis to Program Design, Second Edition32 Rethrowing and Throwing an Exception  When an exception occurs in a try block, control immediately passes to one of the catch blocks.  Typically, a catch block does one of the following:  Completely handles the exception.  Partially processes the exception.  In this case, the catch block either rethrows the same exception or throws another exception for the calling environment to handle the exception.  Rethrows the same exception for the calling environment to handle the exception.

Java Programming: From Problem Analysis to Program Design, Second Edition33 Rethrowing and Throwing an Exception  Useful when:  Catch block catches exception but is unable to handle it.  Catch block decides exception should be handled by calling environment.  Allows programmer to provide exception handling code in one place.  Syntax: throw exceptionReference;

Java Programming: From Problem Analysis to Program Design, Second Edition34 import java.util.*; public class RethrowExceptionExmp1 { static Scanner console = new Scanner(System.in); public static void main(String[] args) { int number; try { number = getNumber(); System.out.println("Line 5: number = " + number); } catch (InputMismatchException imeRef) { System.out.println("Line 7: Exception " + imeRef.toString()); } Rethrowing and Throwing an Exception

Java Programming: From Problem Analysis to Program Design, Second Edition35 public static int getNumber() throws InputMismatchException { int num; try { System.out.print("Line 11: Enter an “ + "integer: "); num = console.nextInt(); System.out.println(); return num; } catch (InputMismatchException imeRef) { throw imeRef; } Rethrowing and Throwing an Exception

Java Programming: From Problem Analysis to Program Design, Second Edition36 The Method printStackTrace  Used to determine the order in which the methods were called and where the exception was handled.

Java Programming: From Problem Analysis to Program Design, Second Edition37 import java.io.*; public class PrintStackTraceExample1 { public static void main(String[] args) { try { methodA(); } catch (Exception e) { System.out.println(e.toString() + " caught in main"); e.printStackTrace(); } The Method printStackTrace

Java Programming: From Problem Analysis to Program Design, Second Edition38 public static void methodA() throws Exception { methodB(); } public static void methodB() throws Exception { methodC(); } public static void methodC() throws Exception { throw new Exception("Exception generated " + " in method C"); } The Method printStackTrace

Java Programming: From Problem Analysis to Program Design, Second Edition39 Sample Run: java.lang.Exception: Exception generated in method C caught in main java.lang.Exception: Exception generated in method C at PrintStackTraceExample1.methodC (PrintStackTraceExample1.java:31) at PrintStackTraceExample1.methodB (PrintStackTraceExample1.java:26) at PrintStackTraceExample1.methodA (PrintStackTraceExample1.java:22) at PrintStackTraceExample1.main (PrintStackTraceExample1.java:11) The Method printStackTrace

Java Programming: From Problem Analysis to Program Design, Second Edition40 Exception-Handling Techniques  Terminate program.  Output appropriate error message upon termination.  Fix error and continue.  Repeatedly get user input.  Output appropriate error message until valid value is entered.  Log error and continue.  Write error messages to file and continue with program execution.

Java Programming: From Problem Analysis to Program Design, Second Edition41 Creating Your Own Exception Classes  Exception class you define extends class Exception or one of its subclasses.  Syntax to throw your own exception object: throw new ExceptionClassName(messageString);

Java Programming: From Problem Analysis to Program Design, Second Edition42 Creating Your Own Exception Classes public class MyDivisionByZeroException extends Exception { public MyDivisionByZeroException() { super("Cannot divide by zero"); } public MyDivisionByZeroException(String strMessage) { super(strMessage); }

Java Programming: From Problem Analysis to Program Design, Second Edition43 Event Handling  Action events:  Handled by implementing interface ActionListener.  Window events:  Handled by implementing interface WindowListener.  Mouse events:  Handled by implementing interface MouseListener.  Key events:  Handled by implementing interface KeyListener.

Java Programming: From Problem Analysis to Program Design, Second Edition44 Event Handling  class WindowAdapter :  Implements interface WindowListener with empty bodies to methods.  class MouseAdapter :  Implements interface MouseListener with empty bodies to methods.

Java Programming: From Problem Analysis to Program Design, Second Edition45 Registering Listeners  To register window listener object to GUI component:  Use method addWindowListener.  Window listener object being registered is passed as parameter to method addWindowListener.  To register mouse listener object to GUI component:  Use method addMouseListener.  Mouse listener object being registered is passed as parameter to method addMouseListener.

Java Programming: From Problem Analysis to Program Design, Second Edition46 Registering Listeners

Java Programming: From Problem Analysis to Program Design, Second Edition47 Registering Listeners

Java Programming: From Problem Analysis to Program Design, Second Edition48 Registering Listeners

Java Programming: From Problem Analysis to Program Design, Second Edition49 Programming Example: Calculator

Java Programming: From Problem Analysis to Program Design, Second Edition50 Chapter Summary  Exception definition  Handling exceptions within a program:  try / catch / finally block.  Order of catch blocks.  Using try / catch blocks in a program.  The class Exception and the Operator instanceof.  Rethrowing and throwing an exception.

Java Programming: From Problem Analysis to Program Design, Second Edition51 Chapter Summary  Exception  Hierarchy  Classes  Checked and unchecked exceptions  The method printStackTrace  Exception handling techniques:  Terminate program.  Fix error and continue.  Log error and continue.  Creating your own exception classes  Event handling