 2006 Pearson Education, Inc. All rights reserved. 1 12 Exception Handling.

Slides:



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

 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
Error Handling in.NET Exceptions. Error Handling Old way (Win32 API and COM): MyFunction() { error_1 = doSomething(); if (error_1) display error else.
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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
 2006 Pearson Education, Inc. All rights reserved. Exception Handling in C++ CS-2303, C-Term Exception Handling in C++ CS-2303 System Programming.
Exception Handling and Format output
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 Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
 Pearson Education, Inc. All rights reserved Exception Handling.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
 2005 Pearson Education, Inc. All rights reserved Exception Handling.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Exception Handling: A Deeper.
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.
C++ Exception Handling
Exception Handling 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
E XCEPTION H ANDLING Chapter 11 C S 442: A DVANCED J AVA P ROGRAMMING.
Microsoft VB 2005: Reloaded, Advanced Chapter 5 Input Validation, Error Handling, and Exception Handling.
 2005 Pearson Education, Inc. All rights reserved Exception Handling.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
Exception Handling An Exception is an indication of a problem that occurs during a program’s execution. Exception handling enables the programmer to create.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
 2009 Pearson Education, Inc. All rights reserved Exception Handling Many slides modified by Prof. L. Lilien (even many without explicit message).
 2006 Pearson Education, Inc. All rights reserved Exception Handling.
 2009 Pearson Education, Inc. All rights reserved Exception Handling.
 2006 Pearson Education, Inc. All rights reserved Exception Handling.
Exception Handling  To use Try blocks to delimit code in which exceptions might occur.  To use Catch blocks to specify exception handlers.  To use the.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
Dr. Abraham. Exception Any problem that VB or OS could not handle Robust program A program that performs well not only under ordinary conditions but also.
 2002 Prentice Hall. All rights reserved. 1 Exception Handling Overview Exception handling –Enable clear, robust and more fault-tolerant programs –Process.
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
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: Exception Handling
Pemrograman VisualMinggu …12… Page 1 MINGGU Ke Duabelas Pemrograman Visual Pokok Bahasan: Exception Handling Tujuan Instruksional Khusus: Mahasiswa dapat.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
VB.Net - Exceptions Copyright © Martin Schray
Introduction to Exception Handling and Defensive Programming.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
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.
Reformatted slides from the textbook, C++ How to Program, 6/e Pearson Education, Inc. All rights reserved Chapter 3. [Lecture 02] Introduction to.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Unit 4 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 23 - Exception Handling Outline 23.1Introduction.
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.
Exception Handling Outline 23.1 Introduction
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Lecture 18B Exception Handling and Richard Gesick.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Enhanced Car Payment Calculator Application Introducing Exception Handling.
Lecture 11 Dr. Eng. Ibrahim El-Nahry Exception Handling.
Appendix H Exception Handling: A Deeper Look
Chapter 11 – Exception Handling
Exception Handling in C++
16 Exception Handling.
13 Exception Handling.
Chapter 14: Exception Handling
Exception Handling and
Exception Handling Chapter 9 Edited by JJ.
16 Exception Handling.
Exception Handling.
Presentation transcript:

 2006 Pearson Education, Inc. All rights reserved Exception Handling

 2006 Pearson Education, Inc. All rights reserved. 2 It is common sense to take a method and try it. If it fails, admit it frankly and try another. But above all, try something. — Franklin Delano Roosevelt O! throw away the worser part of it, And live the purer with the other half. — William Shakespeare

 2006 Pearson Education, Inc. All rights reserved. 3 And oftentimes excusing of a fault Doth make the fault the worse by the excuse. — William Shakespeare If they’re running and they don’t look where they’re going I have to come out from somewhere and catch them. — J. D. Salinger O infinite virtue! com’st thou smiling from the world’s great snare uncaught? — William Shakespeare

 2006 Pearson Education, Inc. All rights reserved. 4 OBJECTIVES In this chapter you will learn:  What exceptions are and how they are handled.  When to use exception handling.  To use try blocks to delimit code in which exceptions might occur.  To throw exceptions to indicate a problem.  To use catch blocks to specify exception handlers.  To use the finally block to release resources.  The.NET exception class hierarchy.  Exception properties.  To create user-defined exceptions.

 2006 Pearson Education, Inc. All rights reserved Introduction 12.2 Exception Handling Overview 12.3 Example: Divide by Zero Without Exception Handling 12.4 Example: Handling DivideByZeroException s and FormatException s Enclosing Code in a try Block Catching Exceptions Uncaught Exceptions Termination Model of Exception Handling Flow of Control When Exceptions Occur 12.5.NET Exception Hierarchy Classes ApplicationException and SystemException Determining Which Exceptions a Method Throws 12.6 finally Block 12.7 Exception Properties 12.8 User-Defined Exception Classes 12.9 Wrap-Up

 2006 Pearson Education, Inc. All rights reserved Introduction Exception – An indication of a problem that occurs during a program’s execution – System.Exception is the base class for all exceptions Exception handling – Resolving exceptions that may occur so program can continue or terminate gracefully – Exception handling enables programmers to create programs that are more robust and fault-tolerant

 2006 Pearson Education, Inc. All rights reserved. 7 Error-Prevention Tip 12.1 Exception handling helps improve a program’s fault tolerance.

 2006 Pearson Education, Inc. All rights reserved Exception Handling Overview Exception Handling – Intermixing program logic with error-handling logic can make programs difficult to read, modify, maintain and debug – Enables programmers to remove error-handling code from the “main line” of the program’s execution – Improves clarity – Enhances modifiability

 2006 Pearson Education, Inc. All rights reserved Example: Divide By Zero Without Exception Handling Analyzing the Results – Thrown exception An exception that has occurred – Throw point Initial point at which the exception occurs – Stack trace Name of the exception in a descriptive message that indicates the problem – DivideByZeroException Occurs when there is a division by zero – FormatException Occurs when the format of an argument does not meet the parameter specifications of the invoked method

 2006 Pearson Education, Inc. All rights reserved. 10 Outline DivideByZeroNoExce ptionHandling.cs (1 of 2) Take and assign inputs from user Divide numerator by denominator

 2006 Pearson Education, Inc. All rights reserved. 11 Outline DivideByZeroNoExce ptionHandling.cs (2 of 2) Exception: division by zero! Exception: denominator is not even a number!

 2006 Pearson Education, Inc. All rights reserved Example: Handling DivideByZeroExceptions and FormatExceptions With exception handling, the program catches and handles (i.e., deals with) the exception Fig displays error message and allows user to enter another set of values

 2006 Pearson Education, Inc. All rights reserved. 13 Outline DivideByZeroTest.cs (1 of 3)

 2006 Pearson Education, Inc. All rights reserved. 14 Outline DivideByZeroTest.cs (2 of 3) try block attempts to read input and perform division Retrieve input; FormatException thrown if input are not valid integers DivideByZeroException thrown if the denominator is 0 Catches any FormatException and DivideByZeroException thrown from the try block, respectively Identifier for the DivideByZeroException The property that returns the exception’s corresponding message

 2006 Pearson Education, Inc. All rights reserved. 15 Outline DivideByZeroTest.cs (3 of 3) (a) (b) (d) (c) (e)

 2006 Pearson Education, Inc. All rights reserved Enclosing Code in a try Block try block – Encloses code that might throw an exception and the code that should not execute if an exception occurs – Keyword try followed by a block of code ( { } ) – There must be at least one catch block and/or finally block immediately after the try block try statement – Consists of try block and corresponding catch and/or finally blocks

 2006 Pearson Education, Inc. All rights reserved Catching Exceptions catch block – Catches (i.e., receives) and handles an exception – Begins with keyword catch – Exception parameter in parentheses Identifies the exception type and enables catch block to interact with caught exception object If parameter-less, able to catch all exceptions types – Executes when exception of proper type matches

 2006 Pearson Education, Inc. All rights reserved Uncaught Exceptions Uncaught exception – There are no matching catch blocks – Program mostly terminates when there is an uncaught exception If debugging in Visual Studio, application pauses and Exception Assistant appears indicating where the exception occured

 2006 Pearson Education, Inc. All rights reserved. 19 Fig | Exception Assistant. Throw point Exception Assistant

 2006 Pearson Education, Inc. All rights reserved Termination Model of Exception Handling When an exception occurs: – try block terminates immediately – Program control transfers to first matching catch block (other catch block(s) are ignored) After exception is handled: – Termination model of exception handling Program control does not return to the throw point because the try block has expired Flow of control proceeds to the first statement after the last catch block – Resumption model of exception handling Program control resumes just after throw point

 2006 Pearson Education, Inc. All rights reserved. 21 Common Programming Error 12.1 Logic errors can occur if you assume that after an exception is handled, control will return to the first statement after the throw point.

 2006 Pearson Education, Inc. All rights reserved. 22 Common Programming Error 12.2 Specifying a comma-separated list of parameters in a catch block is a syntax error. A catch block can have at most one parameter.

 2006 Pearson Education, Inc. All rights reserved NET Exception Hierarchy In C#, only objects of class Exception and its derived classes may be thrown or caught

 2006 Pearson Education, Inc. All rights reserved Classes ApplicationException and SystemException Class Exception – Can be used to catch all exceptions Catch blocks uses is-a relationship – Derived Class ApplicationException s Base class that programmers can extend to create exception classes specific to their application Programs can recover from most ApplicationException s and continue execution – Derived Class SystemException Mainly, this exception can be avoided if coded properly CLR throws SystemException when it becomes unstable

 2006 Pearson Education, Inc. All rights reserved. 25 Common Programming Error 12.3 It is a compilation error if a catch block that catches a base-class exception is placed before a catch block for any of that class’s derived-class types. If this were allowed, the base-class catch block would catch all base-class and derived-class exceptions, so the derived-class exception handler would never execute.

 2006 Pearson Education, Inc. All rights reserved Determining Which Exceptions a Method Throws Methods in the.NET Framework classes – Read the online documentations (MSDN) – If method throws an exception, its description contains a section called Exceptions

 2006 Pearson Education, Inc. All rights reserved. 27 Software Engineering Observation 12.1 If a method throws exceptions, statements that invoke the method directly or indirectly should be placed in try blocks, and those exceptions should be caught and handled.

 2006 Pearson Education, Inc. All rights reserved finally block Programs that obtain certain resources must return them explicitly to avoid resource leaks finally block – Consists of finally keyword followed by a block of code enclosed in curly braces – Optional in a try statement – Placed after the last catch block (if there is one) – Executes whether or not an exception is thrown in the corresponding try block or any of its corresponding catch blocks – Typically contains resource-release code

 2006 Pearson Education, Inc. All rights reserved. 29 Error-Prevention Tip 12.2 The CLR does not completely eliminate memory leaks. The CLR will not garbage collect an object until the program contains no more references to that object. Thus, memory leaks can occur if programmers inadvertently keep references to unwanted objects.

 2006 Pearson Education, Inc. All rights reserved. 30 Error-Prevention Tip 12.3 A finally block typically contains code to release resources acquired in the corresponding try block, which makes the finally block an effective mechanism for eliminating resource leaks.

 2006 Pearson Education, Inc. All rights reserved. 31 Performance Tip 12.1 As a rule, resources should be released as soon as they are no longer needed in a program. This makes them available for reuse promptly.

 2006 Pearson Education, Inc. All rights reserved. 32 Common Programming Error 12.4 Placing the finally block before a catch block is a syntax error.

 2006 Pearson Education, Inc. All rights reserved. 33 Outline UsingExceptions.cs (1 of 8) No exceptions occur No try block needed, exception handled in method

 2006 Pearson Education, Inc. All rights reserved. 34 Outline UsingExceptions.cs (2 of 8) Exception handled outside of method Exception handled outside of method; Exception is rethrown

 2006 Pearson Education, Inc. All rights reserved. 35 Outline UsingExceptions.cs (3 of 8) The finally block executes regardless if there is an exception or not

 2006 Pearson Education, Inc. All rights reserved. 36 Outline UsingExceptions.cs (4 of 8) The finally block executes regardless if there is an exception or not catch block handles any exceptions Throw exception with personalized message

 2006 Pearson Education, Inc. All rights reserved. 37 Outline UsingExceptions.cs (5 of 8) The finally block executes regardless if there is an exception or not Exception is thrown and is not caught inside this method

 2006 Pearson Education, Inc. All rights reserved. 38 Outline UsingExceptions.cs (6 of 8) Throw exception with personalized message Rethrow caught exception

 2006 Pearson Education, Inc. All rights reserved. 39 Outline UsingExceptions.cs (7 of 8) The finally block executes regardless if there is an exception or not

 2006 Pearson Education, Inc. All rights reserved. 40 Outline UsingExceptions.cs (8 of 8)

 2006 Pearson Education, Inc. All rights reserved finally block (Cont.) Throwing Exceptions Using the throw statement – throw statement Throw exceptions Keyword throw followed by the exception object Programmers can throw exceptions from a method if something has gone wrong The string passed through the constructor will be the exception object’s error message

 2006 Pearson Education, Inc. All rights reserved. 42 Common Programming Error 12.5 It is a compilation error if the argument of a throw —an exception object—is not of class Exception or one of its derived classes.

 2006 Pearson Education, Inc. All rights reserved finally block (Cont.) Rethrowing Exceptions – Exceptions are rethrown when a catch block decides either that it cannot process the exception or that it can only partially process it – Exception is rethrown by using keyword throw followed by the reference to the exception that was caught

 2006 Pearson Education, Inc. All rights reserved finally block (Cont.) Returning After a finally block – If the try block successfully completes, or if a catch block catches and handles an exception The program continues its execution with the next statement after the finally block – If an exception is not caught, or if a catch block rethrows an exception Program control continues in the next enclosing try block – The enclosing try could be in the calling method or in one of its callers – If a try block executes and has a corresponding finally block The finally block executes even if the try block terminates due to a return statement

 2006 Pearson Education, Inc. All rights reserved. 45 Common Programming Error 12.6 Throwing an exception from a finally block can be dangerous. If an uncaught exception is awaiting processing when the finally block executes, and the finally block throws a new exception that is not caught in the finally block, the first exception is lost, and the new exception is passed to the next enclosing try block.

 2006 Pearson Education, Inc. All rights reserved. 46 Error-Prevention Tip 12.4 When placing code that can throw an exception in a finally block, always enclose the code in a try statement that catches the appropriate exception types. This prevents the loss of any uncaught and rethrown exceptions that occur before the finally block executes.

 2006 Pearson Education, Inc. All rights reserved. 47 Software Engineering Observation 12.2 Do not place try blocks around every statement that might throw an exception, because this can make programs difficult to read. It is better to place one try block around a significant portion of code, and follow this try block with catch blocks that handle each of the possible exceptions. Then follow the catch blocks with a single finally block. Separate try blocks should be used when it is important to distinguish between multiple statements that can throw the same exception type.

 2006 Pearson Education, Inc. All rights reserved finally block (Cont.) The using Statement – Do not be confused this with the using directive – Simpler way of resource-release code instead of placing in finally block Implicitly places code in try block with corresponding finally block – The resource must be an object that implements IDisposable – Ex: using ( ExampleObject example = new ExampleObject() ) { example.SomeMethod(); }

 2006 Pearson Education, Inc. All rights reserved Exception Properties Exception Properties – Message Stores the error message associated with an Exception object – StackTrace Contains a string that represents the method-call stack

 2006 Pearson Education, Inc. All rights reserved. 50 Error-Prevention Tip 12.5 A stack trace shows the complete method-call stack at the time an exception occurred. This enables the programmer to view the series of method calls that led to the exception. Information in the stack trace includes the names of the methods on the call stack at the time of the exception, the names of the classes in which the methods are defined and the names of the namespaces in which the classes are defined. If the program database (PDB) file that contains the debugging information for the method is available, the stack trace also includes line numbers; the first line number indicates the throw point, and subsequent line numbers indicate the locations from which the methods in the stack trace were called. PDB files are created by the IDE to maintain the debugging information for your projects.

 2006 Pearson Education, Inc. All rights reserved Exception Properties (Cont.) Property InnerException – InnerException Programmers “wrap” exception objects caught in their code so that they then can throw new exception types that are specific to their libraries. If the InnerException property is null, this indicates that the exception was not caused by another exception

 2006 Pearson Education, Inc. All rights reserved Exception Properties (Cont.) Other Exception Properties – HelpLink Specifies location of help file that describe the problem that occurred – Source Specifies the name of the application where the exception occurred – TargetSite Specifies the method where the exception originated

 2006 Pearson Education, Inc. All rights reserved Exception Properties (Cont.) Demonstrating Exception Properties and Stack Unwinding – Stack unwinding When an exception is thrown but not caught in a particular scope (“unwound”) Attempt is made to catch the exception in the outer try block Throwing an Exception with an InnerException – A stack unwinding continues until a catch block catches the exception or the program terminates

 2006 Pearson Education, Inc. All rights reserved. 54 Outline Properties.cs (1 of 4) Outputs exception type and where it occurred Outputs message associated with the exception object Output the method call stack where the exception initially occurred Output the inner wrapped exception

 2006 Pearson Education, Inc. All rights reserved. 55 Outline Properties.cs (2 of 4) Call Method2() Call Method3() Generate exception Rewrap and throw exception

 2006 Pearson Education, Inc. All rights reserved. 56 Outline Properties.cs (3 of 4)

 2006 Pearson Education, Inc. All rights reserved. 57 Outline Properties.cs (4 of 4)

 2006 Pearson Education, Inc. All rights reserved. 58 Error-Prevention Tip 12.6 When catching and rethrowing an exception, provide additional debugging information in the rethrown exception. To do so, create an Exception object containing more specific debugging information, then pass the original caught exception to the new exception object’s constructor to initialize the InnerException property.

 2006 Pearson Education, Inc. All rights reserved User-Defined Exception Classes User-defined exception class – Should derive directly or indirectly from class ApplicationException of namespace System – Class name should end with “Exception” – Recommended to have 3 constructors: Constructor that is parameter-less Constructor that takes in a string argument for the error message Constructor that takes in a string and Exception argument for the error message and inner exception object, respectively

 2006 Pearson Education, Inc. All rights reserved. 60 Good Programming Practice 12.1 Associating each type of malfunction with an appropriately named exception class improves program clarity.

 2006 Pearson Education, Inc. All rights reserved. 61 Software Engineering Observation 12.3 Before creating a user-defined exception class, investigate the existing exceptions in the.NET Framework Class Library to determine whether an appropriate exception type already exists.

 2006 Pearson Education, Inc. All rights reserved. 62 Outline NegativeNumberExce ption.cs (1 of 2) NegativeNumberException extends ApplicationException Calls the base class constructor with exception message Calls the base class constructor with a string

 2006 Pearson Education, Inc. All rights reserved. 63 Outline NegativeNumberExce ption.cs (2 of 2) Calls the base class constructor with a string and an Exception

 2006 Pearson Education, Inc. All rights reserved. 64 Outline SquareRootTest.cs (1 of 3) Throw user defined exception Return square root of the argument

 2006 Pearson Education, Inc. All rights reserved. 65 Outline SquareRootTest.cs (2 of 3) Notify user of the exception

 2006 Pearson Education, Inc. All rights reserved. 66 Outline SquareRootTest.cs (3 of 3) (a) (c) (b) (d)