Chapter 12: Exception Handling

Slides:



Advertisements
Similar presentations
Topics Introduction Types of Errors Exceptions Exception Handling
Advertisements

Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
1 Handling Exceptions COSC 1567 C++ Programming Lecture 11.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
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.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
© The McGraw-Hill Companies, 2006 Chapter 15. © The McGraw-Hill Companies, 2006 Exceptions an exception is an event that occurs during the life of a program.
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.
Microsoft VB 2005: Reloaded, Advanced Chapter 5 Input Validation, Error Handling, and Exception Handling.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Fall 2007CS 225 Program Correctness and Efficiency Chapter 2.
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
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Exception Handling 1. Introduction Users may use our programs in an unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected.
1 Chapter Eight Exception Handling. 2 Objectives Learn about exceptions and the Exception class How to purposely generate a SystemException Learn about.
Object Oriented Programming
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
CIS 270—Application Development II Chapter 13—Exception Handling.
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
Slides Credit Umair Javed LUMS Web Application Development.
Tues. Nov. 25.  An exception is an unexpected error or condition, such as ◦ You issue a command to read a file from a disk, but the file does not exist.
Java Programming: Guided Learning with Early Objects
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
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.
HANDLING EXCEPTIONS Chapter 9. Outline  Learn about the limitations of traditional error-handling methods  Throw exceptions  Use try blocks  Catch.
Unit 4 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Exceptions and Assertions Chapter 15 – CSCI 1302.
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 in C++. Outline What exceptions are and when to use them Using try, catch and throw to detect, handle and indicate exceptions, respectively.
Chapter 9: Completing the Basics. In this chapter, you will learn about: – Exception handling – Exceptions and file checking – The string class – Character.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions in OO Programming Introduction Errors Exceptions in Java Handling exceptions The Try-Catch-Finally mechanism Example code Exception propagation.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Eighth Lecture Exception Handling in Java
Java Programming Fifth Edition
Chapter 14: Exception Handling
Exception Handling Chapter 9.
Exception Handling Chapter 9 Edited by JJ.
Chapter 11: Exception Handling
Exception Handling.
Presentation transcript:

Chapter 12: Exception Handling

Objectives Learn about exceptions Try code and catch exceptions Throw and catch multiple exceptions Use the finally block Understand the advantages of exception handling Java Programming, Seventh Edition

Objectives (cont’d.) Specify the exceptions that a method can throw Trace exceptions through the call stack Create your own Exception classes Use an assertion Java Programming, Seventh Edition

Learning About Exceptions Unexpected or error conditions Not usual occurrences Causes: The program issues a call to a file that does not exist The program attempts to write to a full disk The user enters invalid data The program attempts to divide a value by 0 Java Programming, Seventh Edition

Learning About Exceptions (cont’d.) Exception handling Object-oriented techniques used to manage Exception errors Runtime exceptions Exceptions Objects Descend from the Throwable class Java Programming, Seventh Edition

Java Programming, Seventh Edition

Learning About Exceptions (cont’d.) Error class Represents serious errors from which a program usually cannot recover Error condition A program runs out of memory A program cannot locate a required class Java Programming, Seventh Edition

Learning About Exceptions (cont’d.) Exception class Less serious errors Unusual conditions A program can recover from this type of error Exception class errors An invalid array subscript Performing illegal arithmetic operations Java Programming, Seventh Edition

Learning About Exceptions (cont’d.) Java Programming, Seventh Edition

Learning About Exceptions (cont’d.) Java Programming, Seventh Edition

Learning About Exceptions (cont’d.) You do not necessarily have to deal with an exception Let the offending program terminate But doing so is abrupt and unforgiving You can write programs without using exception-handling techniques Use a decision to avoid an error Exception handling provides a more elegant solution for handling error conditions Java Programming, Seventh Edition

Learning About Exceptions (cont’d.) Fault-tolerant Designed to continue to operate when some part of the system fails Robustness Represents the degree to which a system is resilient to stress Java Programming, Seventh Edition

Trying Code and Catching Exceptions try block A segment of code in which something might go wrong Attempts to execute Acknowledges an exception might occur A try block includes: The keyword try Opening and closing curly braces Executable statements, which might cause an exception Java Programming, Seventh Edition

Trying Code and Catching Exceptions (cont’d.) catch block A segment of code Immediately follows a try block Handles an exception thrown by the try block preceding it Can “catch” an Object of type Exception or an Exception child class throw statement Sends an Exception object out of a block or method so it can be handled elsewhere Java Programming, Seventh Edition

Trying Code and Catching Exceptions (cont’d.) A catch block includes: The keyword catch Opening and closing parentheses An Exception type A name for an instance of the Exception type Opening and closing curly braces Statements to handle the error condition Java Programming, Seventh Edition

Trying Code and Catching Exceptions (cont’d.) Java Programming, Seventh Edition

Trying Code and Catching Exceptions (cont’d.) If no exception occurs within the try block, the catch block does not execute getMessage() method Obtains information about the exception Within a catch block, you might want to add code to correct the error Java Programming, Seventh Edition

Trying Code and Catching Exceptions (cont’d.) Java Programming, Seventh Edition

Using a try Block to Make Programs “Foolproof” It is useful to circumvent data entry errors Handle potential data conversion exceptions caused by careless users Using a nextLine() call will account for potential remaining characters in the input buffer Java Programming, Seventh Edition

Using a try Block to Make Programs “Foolproof” (cont’d.) Figure 12-12 The EnteringIntegers program Java Programming, Seventh Edition

Using a try Block to Make Programs “Foolproof” (cont’d.) Figure 12-14 A typical execution of the EnteringIntegers program with the extra nextLine() call Java Programming, Seventh Edition

Declaring and Initializing Variables in try…catch Blocks A variable declared within a block is local to that block It goes out of scope when the try or catch block ends If the conversion fails, an exception is thrown Java Programming, Seventh Edition

Declaring and Initializing Variables in try…catch Blocks (cont’d.) Figure 12-15 The UninitializedVariableTest program Java Programming, Seventh Edition

Declaring and Initializing Variables in try…catch Blocks (cont’d.) Figure 12-16 The error message generated when compiling the UninitializedVariableTest program Java Programming, Seventh Edition

Throwing and Catching Multiple Exceptions You can place multiple statements within a try block Only the first error-generating statement throws an exception When a program contains multiple catch blocks: They are examined in sequence until a match is found for the Exception type The matching catch block executes Each remaining catch block is bypassed Java Programming, Seventh Edition

Figure 12-18 The DivisionMistakeCaught3 class Java Programming, Seventh Edition

Throwing and Catching Multiple Exceptions (cont’d.) “Catch-all” block Accepts a more generic Exception argument type: catch(Exception e) Unreachable code Program statements that can never execute under any circumstances In Java 7, a catch block can also be written to catch multiple Exception types It is poor style for a method to throw more than three or four Exception types Java Programming, Seventh Edition

Figure 12-20 The DivisionMistakeCaught4 application Java Programming, Seventh Edition

Using the finally Block Use for actions you must perform at the end of a try…catch sequence Use to perform cleanup tasks Executes regardless of whether the preceding try block identifies an exception Java Programming, Seventh Edition

Using the finally Block (cont’d.) Figure 12-24 Format of try…catch…finally sequence Java Programming, Seventh Edition

Using the finally Block (cont’d.) When the try code fails: It throws an exception The Exception object is caught The catch block executes Control passes to statements at the end of the method Java Programming, Seventh Edition

Using the finally Block (cont’d.) Reasons the final set of statements might never execute: An unplanned exception might occur The try or catch block might contain a System.exit(); statement The try block might throw an Exception object for which you did not provide a catch block Program execution stops immediately The exception is sent to the operating system for handling The current method is abandoned Java Programming, Seventh Edition

Using the finally Block (cont’d.) When the finally block is used, finally statements execute before the method is abandoned The finally block executes no matter what outcome of the try block occurs The try ends normally The catch executes The exception causes the method to abandon prematurely Java Programming, Seventh Edition

Understanding the Advantages of Exception Handling Before object-oriented programming languages, errors were handled with confusing, error-prone methods When any method fails, the program sets appropriate error code Difficult to follow The application’s purpose and intended outcome are lost in a maze of if statements Coding mistakes are made because of complicated nesting Java Programming, Seventh Edition

Understanding the Advantages of Exception Handling (cont’d.) Figure 12-26 Pseudocode representing traditional error checking Java Programming, Seventh Edition

Understanding the Advantages of Exception Handling (cont’d.) Figure 12-27 Pseudocode representing object-oriented exception handling Java Programming, Seventh Edition

Understanding the Advantages of Exception Handling (cont’d.) Java’s object-oriented, error-handling technique Statements of the program that do the “real” work are placed together, where their logic is easy to follow Unusual, exceptional events are grouped and moved out of the way An advantage to object-oriented exception handling is flexibility in handling of error situations Appropriately deal with exceptions as you decide how to handle them Java Programming, Seventh Edition

Specifying the Exceptions That a Method Can Throw If a method throws an exception that it will not catch but will be caught by a different method, use the keyword throws followed by the Exception type in the method header Exception specification Lists exceptions that a method may throw Every Java method has the potential to throw an exception For most Java methods, do not use the throws clause Let Java handle any exception by shutting down the program Most exceptions never have to be explicitly thrown or caught Java Programming, Seventh Edition

Specifying the Exceptions That a Method Can Throw (cont’d.) Checked exceptions Programmers should anticipate checked exceptions Programs should be able to recover from them Unchecked exceptions Inherit from the Error class or the RuntimeException class You are not required to handle these exceptions You can simply let the program terminate An example is dividing by zero Java Programming, Seventh Edition

Specifying the Exceptions That a Method Can Throw (cont’d.) If you throw a checked exception from a method, you must do one of the following: Catch it Declare the exception in the method header’s throws clause To use a method to its full potential, you must know the: Method’s name Method’s return type Type and number of arguments the method requires Type and number of exceptions the method throws Java Programming, Seventh Edition

Tracing Exceptions Through the Call Stack The memory location where the computer stores the list of method locations to which the system must return When a method throws an exception: The exception is thrown to the next method up the call stack Methods are allowed to handle exceptions wherever the programmer has decided it is most appropriate Including allowing the operating system to handle the error Java Programming, Seventh Edition

Tracing Exceptions Through the Call Stack (cont’d.) Figure 12-32 Cycling through the call stack Java Programming, Seventh Edition

Tracing Exceptions Through the Call Stack (cont’d.) printStackTrace() method Displays a list of methods in the call stack Determines the location of an exception Do not place in a finished program Most useful for diagnosing problems Java Programming, Seventh Edition

Creating Your Own Exception Classes Java provides over 40 categories of Exceptions Java allows you to create your own Exception classes Extend a subclass of Throwable Exception class constructors: Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause) Java Programming, Seventh Edition

Using Assertions Assertion assert statement A Java language feature Detects logic errors Debugs programs assert statement Creates an assertion, such as: assert booleanExpression : optionalErrorMessage The Boolean expression in the assert statement should always be true if the program is working correctly Java Programming, Seventh Edition

Using Assertions (cont’d.) An AssertionError is thrown when a condition is false To enable an assertion, you must use the -ea option when executing a program Java Programming, Seventh Edition

You Do It Throwing and Catching an Exception Using Multiple catch Blocks Creating a Class That Automatically Throws Exceptions Creating a Class That Passes on an Exception Object Creating an Application That Can Catch Exceptions Extending a Class That Throws Exceptions Creating an Exception Class Using an Exception You Created Java Programming, Seventh Edition

Don’t Do It Don’t forget that all the statements in a try block might not execute Don’t forget you might need a nextLine() method call after an attempt to read numeric data from the keyboard throws an exception Don’t forget that a variable declared in a try block goes out of scope at the end of the block Don’t forget that when a variables get its usable value within a try block, you must ensure that it has a valid value before attempting to use it Java Programming, Seventh Edition

Don’t Do It (cont’d.) Don’t forget to place more specific catch blocks before more general ones Don’t forget to write a throws clause for a method that throws an exception but does not handle it Don’t forget to handle any checked exception thrown to your method Java Programming, Seventh Edition

Summary Exception Exception handling An unexpected or error condition Exception handling Object-oriented techniques to manage errors Basic classes of errors: Error and Exception Exception-handling code try block catch block finally block Java Programming, Seventh Edition

Summary (cont’d.) Use the throws <name>Exception clause after the method header Indicate the type of exception that might be thrown Call stack A list of method locations to which the system must return Java provides over 40 categories of Exceptions Create your own Exception classes Assertion State a condition that should be true Java throws an AssertionError when it is not Java Programming, Seventh Edition