Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2009 Pearson Education, Inc. All rights reserved. 1 13 Exception Handling Many slides modified by Prof. L. Lilien (even many without explicit message).

Similar presentations


Presentation on theme: " 2009 Pearson Education, Inc. All rights reserved. 1 13 Exception Handling Many slides modified by Prof. L. Lilien (even many without explicit message)."— Presentation transcript:

1  2009 Pearson Education, Inc. All rights reserved. 1 13 Exception Handling Many slides modified by Prof. L. Lilien (even many without explicit message). Slides added by L.Lilien are © 2006-2009 Leszek T. Lilien. Permision to use for non-commercial purposes slides added by L.Lilien’s will be gladly granted upon a written (e.g., emailed) request.

2  2009 Pearson Education, Inc. All rights reserved. 2 13.1 Introduction 13.2 Exception Handling Overview 13.3 Example: Divide by Zero without Exception Handling 13.4 Example: Handling DivideByZeroException s and FormatException s 13.5.NET Exception Hierarchy 13.6 finally Block 13.7 Exception Properties 13.8 User-Defined (Programmer-Defined) Exception Classes

3  2009 Pearson Education, Inc. All rights reserved. 3 13.1 Introduction Exception – Indication of a problem during program execution - Problems are exceptional, normally no problems Exception handling – Enables programmers to create application that can handle exceptions - Enable clear, robust and more fault-tolerant programs Slide modified by L. Lilien

4  2009 Pearson Education, Inc. All rights reserved. 4 ++READ LATER++ 13.1 Introduction (Cont.) Error-Prevention Tip 13.1 Exception handling helps improve a program’s fault tolerance.

5  2009 Pearson Education, Inc. All rights reserved. 5 13.2 Exception Handling Overview Pseudocode with included error processing code Perform a task If the preceding task did not execute correctly Perform error processing Perform next task If the preceding task did not execute correctly Perform error processing … Slide added by L. Lilien

6  2009 Pearson Education, Inc. All rights reserved. 6 13.2 Exception Handling Overview – Cont. Including error processing code in a program intermixes program logic with error-handling logic – Difficult to read, maintain, debug – Better to separate program logic from error-handling logic - Errors happen infrequently - If many errors, placing checks for errors in program slows it down unnecessarily Unnecessarily bec. most checks will not find errors Exception handling allows to remove error-handling code from the “main line” program execution – Improves program clarity – Enhances modifiability Slide modified by L. Lilien

7  2009 Pearson Education, Inc. All rights reserved. 7 13.2 Exception Handling Overview – Cont. Keywords for exception handling – try { } – catch ( ) // 1 or more following each try { } Note: If no “( )”, catch handles all exception types – finally // optional, follows catch { } We’ll see how they are used in an example Slide added by L. Lilien

8  2009 Pearson Education, Inc. All rights reserved. 8 ++READ LATER++ 13.2 Exception Handling Overview – Cont. How exception detected? – By a method called in a program – By CLR (Common Language Runtime) system What happens when exception detected? – Method or CLR throws an exception - Throw point – point at which exception was thrown Important for debugging Exceptions are objects – Inherit from System.Exceptions

9  2009 Pearson Education, Inc. All rights reserved. 9 ++READ LATER++ 13.2 Exception Handling Overview – Cont. Exception handling scenario – Exception occurs in a try block – The try block expires (terminates immediately) - Therefore, we say that C# follows the termination model of exception handling – CLR searches for the catch block (associated with this try block) matching the exception - Among n catch blocks following this try block - ‘Matching” – comparing the thrown exception’s type T1 and catch’s exception parameter type T2 Match – if they are identical or T1 is a derived class of T2 – If a match: (a) Code within the catch handler is executed (b) Remaining catch blocks are ignored – Execution resumed at the first instruction following this try- catch sequence Slide modified by L. Lilien

10  2009 Pearson Education, Inc. All rights reserved. 10 ++READ LATER++ 13.2 Exception Handling Overview – Cont. If no exception in a try block => catch blocks for this try are ignored – Execution resumed at the first instruction following this try-catch sequence IF no matching catch or: IF exception occurs in a statement that is not in a try block THEN: – the method containing the statement terminates immediately – CLR attempts to locate an enclosing try block in a calling method (this is called “Stack unwinding”) Slide modified by L. Lilien

11  2009 Pearson Education, Inc. All rights reserved. 11 13.3 Example: Divide by Zero without Exception Handling ++READ LATER++ If you run using Debug > Start Debugging, the program pauses at the line where an exception occurs (see p. 593/-1) If you run using the application: - from a Command Prompt window (see p. 595/1-ed.3) – OR - walking down directory hierarchy down to …/ /bin/debug – When an error arises, a dialog indicates that the application has encountered a problem and needs to close – An error message describing the problem is displayed

12  2009 Pearson Education, Inc. All rights reserved. 12 Outline DivideByZeroNo ExceptionHandling.cs ( 1 of 2 ) Example problem: Calculate integer result of dividing one input integer by another input integer. In this example, we have no explicit exception handling Still, the system throws an exception when a method detects a problem (next slide) Converting values can cause a FormatException.

13  2009 Pearson Education, Inc. All rights reserved. 13 Outline Division can cause a DivideByZeroException. DivideByZeroNo ExceptionHandling.cs ( 2 of 2 ) Stack trace

14  2009 Pearson Education, Inc. All rights reserved. 14 ++READ LATER++ 13.3 Example: Divide by Zero without Exception Handling (Cont.) Additional information — known as a stack trace — displays the exception name and the path of execution that led to the exception. Each “ at ” line in the stack trace indicates a line of code in the particular method that was executing when the exception occurred. This information tells where the exception originated, and what method calls were made to get to that point.

15  2009 Pearson Education, Inc. All rights reserved. 15 ++READ LATER++ 13.3 Example: Divide by Zero without Exception Handling (Cont.) When entered “0” as denominator : – A DivideByZeroException occurs - Since can’t divide by zero When entered “hello” as denominator : – A FormatException occurs - Since method Convert. ToInt32 receives a string that is not a valid integer Note: A program may continue executing even though an exception has occurred and a stack trace has been printed – In such cases, the application may produce incorrect results

16  2009 Pearson Education, Inc. All rights reserved. 16 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions ++READ LATER++ The Int32.TryParse method converts a string to an int value if possible – It requires two arguments - one is the string to parse - the other is the variable in which the converted value is to be stored – It returns true if the string was parsed successfully – If the string could not be converted, the value 0 is assigned to the second argument

17  2009 Pearson Education, Inc. All rights reserved. 17 Outline a) Performing integer division b) Dividing by zero d) Entering a string value e) Error message c) Error message DivideByZeroTest.cs ( 4 of 4 ) Expected behavior of the next WF app:

18  2009 Pearson Education, Inc. All rights reserved. 18 This Windows Forms app uses exception handling to process DivideByZeroException s and FormatException s This program demonstrates how to catch and handle such exceptions Outline DivideByZeroTest.cs ( 1 of 3 )

19  2009 Pearson Education, Inc. All rights reserved. 19 Outline DivideByZeroTest.cs ( 2 of 3 ) This catch block catches and handles a FormatException. This catch block catches and handles a DivideBy- ZeroException.

20  2009 Pearson Education, Inc. All rights reserved. 20 Outline a) Performing integer division b) Dividing by zero d) Entering a string value e) Error message c) Error message DivideByZeroTest.cs ( 3 of 3) Output of DivideByZeroTest program

21  2009 Pearson Education, Inc. All rights reserved. 21 ++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions Error catching (by a method or CLR) – Method Convert.ToInt32 will automatically detect invalid representations of an integer - Method generates a FormatException – CLR automatically detects division by zero - CLR generates a DivideByZeroException

22  2009 Pearson Education, Inc. All rights reserved. 22 ++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.) 13.4.1 Enclosing Code in a try Block A try block encloses code that might throw exceptions and code that is skipped when an exception occurs.

23  2009 Pearson Education, Inc. All rights reserved. 23 ++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.) 13.4.2 Catching Exceptions When an exception occurs in a try block, a corresponding catch block catches the exception and handles it – At least one catch block must immediately follow a try block. A catch block can specify an exception parameter representing the exception that the catch block can handle – Optionally, you can include a catch block that does not specify an exception type to catch all exception types.

24  2009 Pearson Education, Inc. All rights reserved. 24 ++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.) 13.4.3 Uncaught Exceptions An uncaught exception (or unhandled exception) is an exception for which there is no matching catch block

25  2009 Pearson Education, Inc. All rights reserved. 25 ++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.) Throw pointException Assistant When you run the application from Visual Studio with debugging, a window called the Exception Assistant (Fig. 13.3-below) appears.

26  2009 Pearson Education, Inc. All rights reserved. 26 ++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.) 13.4.4 Termination Model of Exception Handling When a method called in a program or the CLR detects a problem, the method or the CLR throws an exception – The point at which an exception occurs is called the throw point

27  2009 Pearson Education, Inc. All rights reserved. 27 ++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.) Two kinds of exception handling (p.600/2 -ed.3) : 1)“Terminate” model of exception handling – used in C# After exception handling, control resumes after the last catch block 2) “Resumption” model of exception handling After exception handling, control resumes just after the throw point Slide modified by L. Lilien

28  2009 Pearson Education, Inc. All rights reserved. 28 ++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.) If an exception occurs in a try block, program control immediately transfers to the first catch block matching the type of the thrown exception After the exception is handled, program control in C# resumes after the last catch block – Since C# uses the termination model of exception handling

29  2009 Pearson Education, Inc. All rights reserved. 29 ++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.) Common Programming Error 13.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. Common Programming Error 13.2 A catch block can have at most one parameter Specifying a comma-separated list of parameters in a catch block is a syntax error

30  2009 Pearson Education, Inc. All rights reserved. 30 13.5.NET Exception Hierarchy.NET Framework exception hierarchy (in the System namespace) – Base class Exception – Derived class ApplicationException – Derived class SystemException - Derived class IndexOutOfRangeException Thrown, e.g., on an attempt to access out-of-range array subscript - Derived class NullReferenceException Thrown, e.g., on an attempt to reference a non-existing object - Derived class … (many others)… In C#, exception-handling mechanisms allows to throw/catch only objects of class Exception and its derived classes Slide modified by L. Lilien

31  2009 Pearson Education, Inc. All rights reserved. 31 13.5.NET Exception Hierarchy (Cont.) Derived class ApplicationException – Programmers use it to create exception classes specific to their applications – Low risk of program stopping upon ApplicationException - Typically, programs can recover from ApplicationExceptions & continue execution Derived class SystemException – CLR can generate runtime exceptions (derived from SystemException) at any point during execution - Many can be avoided by proper coding - E.g., runtime exception: IndexOutOfRangeException - E.g., runtime reference to a non-existing object: NullReferenceException – Typically, programs terminate upon SystemException - Bec. programs can’t recover from most SystemExceptions Slide modified by L. Lilien

32  2009 Pearson Education, Inc. All rights reserved. 32 ++READ LATER++ 13.5.NET Exception Hierarchy (Cont.) Is MSDN Library (which provides Help) installed in your Visual Studio? – If not, get it from C-208, and install it See full hierarchy of exception classes in.NET in Visual Studio : – Select >>Help>Index – Look up “Exception class” Benefit of exception hierarchy: – Instead of catch -ing each derived-class exception class separately, catch the base-class exception – Much more concise – Useful only if the handling behavior is the same for the base class and the derived classes Slide added by L. Lilien

33  2009 Pearson Education, Inc. All rights reserved. 33 ++READ LATER++ 13.5.NET Exception Hierarchy (Cont.) How to find out that a program can cause an exception? 1) For methods in.NET Framework - Look at detailed method description in Visual Studio Select >>Help>Index Find the class.method in the index Look up the “Exception” section in the document describing the method  Enumerates exceptions of the method  Describes the reason why each occurs - Example (p.603/1-ed.3) – Convert.ToInt32 can throw 2 exception types: FormatException and OverflowException 2) For CLR … next page… Slide added by L. Lilien

34  2009 Pearson Education, Inc. All rights reserved. 34 How to find out that a program can cause an exception? (Cont.) 2) For CLR - More difficult – search C# Language Specifications (online) (on MSDN online at the Visual C# Developer Center: http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx )Visual C# Developer Center http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx - In Visual Studio The C# Language Specification available in Microsoft Word in the VC#\Specifications\1033\ directory under your Visual Studio 2008 installation directory (e.g., in: C:\Program Files\Microsoft Visual Studio 9.0\VC#\Specifications\1033 ) - Example: DivideByZeroException described in Section 16.4 (p. 419) of “C# Language Specification:” Thrown when an attempt to divide an integral value by zero occurs. Slide added by L. Lilien ++READ LATER++ 13.5.NET Exception Hierarchy (Cont.)

35  2009 Pearson Education, Inc. All rights reserved. 35 A catch block can use a base-class type to catch a hierarchy of related exceptions A catch block that specifies a parameter of type Exception can catch all exceptions – This technique makes sense only if the handling behavior is the same for a base class and all derived classes Common Programming Error 13.3 The compiler issues an 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 In this case, the base-class catch block would catch all base-class and derived-class exceptions, so the derived-class exception handler would never execute—a possible logic error ++READ LATER++ 13.5.NET Exception Hierarchy

36  2009 Pearson Education, Inc. All rights reserved. 36 ++READ LATER++ 13.5.NET Exception Hierarchy (Cont.) 13.5.2 Determining Which Exceptions a Method Throws Example – determine which exceptions are thrown by Convert.ToInt32 method – Search for “ Convert.ToInt32 method ” in the Index of the VS online documentation – Select the document entitled Convert.ToInt32 Method ( System ) – In the document that describes the method, click the link ToInt32(String ) – The Exceptions section indicates that method Convert.ToInt32 throws two exception types

37  2009 Pearson Education, Inc. All rights reserved. 37 ++READ LATER++ 13.5.NET Exception Hierarchy (Cont.) Software Engineering Observation 13.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

38  2009 Pearson Education, Inc. All rights reserved. 38 13.6 finally Block Programs frequently request and release resources dynamically Example 1: – Memory is allocated for each object created (with new) – Once object not needed, memory used by it should be released – If memory is not released, memory leak (a specific type of a resource leak) occurs ++SKIP++: Example 2: – Operating systems typically prevent more than one program from manipulating a file – Therefore, the program that needs file no more, should close it (i.e., release the file, a resource) so other programs can use it – If the file is not closed, a resource leak occurs

39  2009 Pearson Education, Inc. All rights reserved. 39 13.6 finally Block (Cont.) So, resource leak can be defined as: – Allocation of resources (files, memory, etc.) lasting too long - Longer than needed finally block – Associated with a try block – Ideal for placing resource deallocation code - Prevents leak of resources allocated in its try block – Executed immediately after catch handler or try block – Required if no catch block is present Optional if one or more catch handlers exist – Executed if its try block entered - Even if try block not completed Slide modified by L. Lilien

40  2009 Pearson Education, Inc. All rights reserved. 40 Error-Prevention Tip 13.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 and even then there may be a delay until the memory is required Thus, memory leaks can occur if programmers inadvertently keep references to unwanted objects (i.e., the objects not needed any more) ++READ LATER++ 13.6 finally Block (Cont.)

41  2009 Pearson Education, Inc. All rights reserved. 41 ++READ LATER++ 13.6 finally Block (Cont.) Exceptions often occur while processing resources Regardless of whether a program experiences exceptions, the program should close the file when it is no longer needed C# provides the finally block, which is guaranteed to execute regardless of whether an exception occurs This makes the finally block ideal to release resources from the corresponding try block

42  2009 Pearson Education, Inc. All rights reserved. 42 ++READ LATER++ 13.6 finally Block (Cont.) Local variables in a try block cannot be accessed in the corresponding finally block, so variables that must be accessed in both should be declared before the try block. Error-Prevention Tip 13.3 A finally block typically contains code to release resources acquired in the corresponding try block This makes the finally block an effective mechanism for eliminating resource leaks

43  2009 Pearson Education, Inc. All rights reserved. 43 ++READ LATER++ 13.6 finally Block (Cont.) Performance Tip 13.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 Common Programming Error 13.4 Placing the finally block before a catch block is a syntax error

44  2009 Pearson Education, Inc. All rights reserved. 44 13.6 finally Block (Cont.) The throw statement – Allows a user/programmer to throw an exception at will - E.g.: throw new Exception("Exception in ThrowTest Method" ); - w here the string passed to exception object’s constructor becomes exception object’s error message – Can throw only an object of class Exception or one of its derived classes (SystemException, MyDivBbZeroException, etc) – You can customize the exception type thrown from methods Slide modified by L. Lilien

45  2009 Pearson Education, Inc. All rights reserved. 45 Outline UsingExceptions.cs ( 1 of 8) This application (below) demonstrates that the finally block always executes (even when no exception occurs) Main invokes method DoesNotThrowException. Main invokes method ThrowExceptionWithCatch. Calling DoesNotThrowException In DoesNotThrowException finally executed in DoesNotThrowException End of DoesNotThrowException Calling ThrowExceptionWithCatch In ThrowExceptionWithCatch Message: Exception in ThrowExceptionWithCatch finally executed in ThrowExceptionWithCatch End of ThrowExceptionWithCatch Calling ThrowExceptionWithoutCatch

46  2009 Pearson Education, Inc. All rights reserved. 46 Outline UsingExceptions.cs ( 2 of 8) Main invokes method ThrowExceptionWithoutCatch. Main invokes method ThrowExceptionCatchRethrow. In ThrowExceptionWithoutCatch finally executed in ThrowExceptionWithoutCatch Caught exception from ThrowExceptionWithoutCatch in Main Calling ThrowExceptionCatchRethrow In ThrowExceptionCatchRethrow Message: Exception in ThrowExceptionCatchRethrow finally executed in ThrowExceptionCatchRethrow

47  2009 Pearson Education, Inc. All rights reserved. 47 Outline Because the try block does not throw any exceptions, the catch block is ignored. UsingExceptions.cs ( 3 of 8) Caught exception from ThrowExceptionCatchRethrow in Main Calling DoesNotThrowException In DoesNotThrowException

48  2009 Pearson Education, Inc. All rights reserved. 48 Outline The finally block always executes. The try block throws an exception. The catch and finally blocks execute when the exception occurs. UsingExceptions.cs ( 4 of 8) finally executed in DoesNotThrowException End of DoesNotThrowException Calling ThrowExceptionWithCatch In ThrowExceptionWithCatch Message: Exception in ThrowExceptionWithCatch

49  2009 Pearson Education, Inc. All rights reserved. 49 Outline The catch and finally blocks execute when the exception occurs. The try block throws an exception. UsingExceptions.cs ( 5 of 8) finally executed in ThrowExceptionWithCatch End of ThrowExceptionWithCatch Calling ThrowExceptionWithoutCatch In ThrowExceptionWithoutCatch

50  2009 Pearson Education, Inc. All rights reserved. 50 Outline The finally block executes but the exception remains uncaught until after control returns to Main. The try block throws an exception. UsingExceptions.cs ( 6 of 8) finally executed in ThrowExceptionWithoutCatch Caught exception from ThrowExceptionWithoutCatch in Main Calling ThrowExceptionCatchRethrow In ThrowExceptionCatchRethrow Statements following finally are not executed. The reason: there is an unhandled exception when finally finishes, so once the finally block is completed, execution returns to Main.

51  2009 Pearson Education, Inc. All rights reserved. 51 Outline The catch block rethrows the exception, which is then caught after control returns to Main. The catch and finally blocks execute when the exception occurs. UsingExceptions.cs ( 7 of 8) Message: Exception in ThrowExceptionCatchRethrow finally executed in ThrowExceptionCatchRethrow Caught exception from ThrowExceptionCatchRethrow in Main Statements following finally are not executed. The reason: there is an unhandled exception when finally finishes, so once the finally block is completed, execution returns to Main.

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

53  2009 Pearson Education, Inc. All rights reserved. 53 Common Programming Error 13.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. Common Programming Error 13.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. ++READ LATER++ 13.6 finally Block (Cont.)

54  2009 Pearson Education, Inc. All rights reserved. 54 Error-Prevention Tip 13.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 Software Engineering Observation 13.2 Do not place try blocks around every statement that might throw an exception— this can make programs difficult to read It’s better to place one try block around a significant portion of code, and follow this try block with catch blocks that handle each possible exception 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 ++READ LATER++ 13.6 finally Block (Cont.)

55  2009 Pearson Education, Inc. All rights reserved. 55 ++READ LATER++ 13.6 finally Block (Cont.) The using statement simplifies writing code in which you obtain a resource. The general form of a using statement is: using ( ExampleObject e = new ExampleObject() ) { e.SomeMethod(); } Read subsection on the using statement - not to be confused with the using directive for using namespaces – p. 610 (ed.3)

56  2009 Pearson Education, Inc. All rights reserved. 56 ++READ LATER++ 13.6 finally Block (Cont.) The using statement code is equivalent to { ExampleObject e = new ExampleObject(); try { e.SomeMethod(); } finally { if ( e != null ) ( ( IDisposable ) e ).Dispose(); } } NOTE: Some components above were not discussed yet in class.

57  2009 Pearson Education, Inc. All rights reserved. 57 13.7 Exception Properties Exception properties = properties of the Exception class Caught Exception objects have 3 properties (all shown in the next example) 1) Property Message Cf. Slide 50, line 121: exception object ‘exceptionParameter’ Console.WriteLine( "Message: " + exceptionParameter.Message ); - Stores the error message associated with an Exception object May be a default message or customized 2) Property StackTrace - Contains a string that represents the method call stack - Represents sequential list of methods that were not fully processed when the exception occurred - throw point - the exact location where exception occurred

58  2009 Pearson Education, Inc. All rights reserved. 58 13.7 Exception Properties (Cont.) Properties for a caught exception – cont. 3) Property InnerException - Programmers “wrap” exception objects caught in their own code Then can throw new exception types specific to their own code - The original exception object remains “saved” in Inner Exception within the programmer- defined exception - Example: l. 26-27 in the following program

59  2009 Pearson Education, Inc. All rights reserved. 59 Outline Our next example (below) demonstrates properties of class Exception and stack unwinding Properties.cs ( 1 of 5 )

60  2009 Pearson Education, Inc. All rights reserved. 60 Outline Outputting properties of class Exception. Method1 and Method2 are added to the method stack, and then unwind when they do not catch Method3 ’s exception. Properties.cs ( 2 of 5 )

61  2009 Pearson Education, Inc. All rights reserved. 61 Outline Method1 and Method2 are added to the method stack, and then unwind when they do not catch Method3 ’s exception. Method3 catches then rethrows the exception. Properties.cs ( 3 of 5 )

62  2009 Pearson Education, Inc. All rights reserved. 62 Outline Properties.cs ( 4 of 5 ) exceptionParameter.Message starts and ends here (highlighted, < 1 line) exceptionParameter.StackTrace starts here exceptionParameter.InnerException starts here

63  2009 Pearson Education, Inc. All rights reserved. 63 Outline Properties.cs ( 5 of 5 )

64  2009 Pearson Education, Inc. All rights reserved. 64 ++READ LATER++ 13.7 Exception Properties (Cont.) Error-Prevention Tip 13.5 If the program database (PDB) file (that contains the debugging information for a method) is accessible to the IDE, 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

65  2009 Pearson Education, Inc. All rights reserved. 65 ++READ LATER++ 13.7 Exception Properties (Cont.) When an exception occurs, a programmer might use a different error message or indicate a new exception type The original exception object is stored in the InnerException property

66  2009 Pearson Education, Inc. All rights reserved. 66 ++READ LATER++ 13.7 Exception Properties (Cont.) Class Exception provides also other properties: – HelpLink specifies the location of a help file that describes the problem – Source specifies the name of the application or object that caused the exception – TargetSite specifies the method where the exception originated.

67  2009 Pearson Education, Inc. All rights reserved. 67 ++READ LATER++ 13.7 Exception Properties (Cont.) The method called most recently appears at the top of the stack; the first method called ( Main ) appears at the bottom The StackTrace represents the state of the method-call stack at the throw point The inner-exception information includes the inner exception stack trace Error-Prevention Tip 13.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.

68  2009 Pearson Education, Inc. All rights reserved. 68 User can create customized (a.k.a. user-defined or programmer- defined) exception classes – Specific to the problems that occur in user’s program They should be derived from the class ApplicationException – Which is in turn derived from the class Exception 13.8 User-Defined (Programmer- Defined) Exception Classes

69  2009 Pearson Education, Inc. All rights reserved. 69 Customized exception classes – Class name should end with “Exception” - E.g., NegativeNumberException – Should define three constructors - a parameterless constructor - a constructor that receives a string argument (the error message) - a constructor that receives a string argument and an Exception argument (the error message and the inner exception object) – User-defined exceptions must be well documented - So that other developers will know how to handle them Example of customized exception types (classes) – next Slide ++READ LATER++ 13.8 User-Defined (Programmer-Defined) Exception Classes

70  2009 Pearson Education, Inc. All rights reserved. 70 Outline NegativeNumber Exception.cs ( 1 of 2 ) Class NegativeNumberException (Fig. 13.6 - below) defines customized exceptions that occur when a program performs an illegal operation on a negative number. Inheriting from class Exception. Parameterless constructor.

71  2009 Pearson Education, Inc. All rights reserved. 71 Outline Constructor with two arguments (the Message and InnerException ). NegativeNumber Exception.cs ( 2 of 2 ) Constructor with a single argument (the Message ).

72  2009 Pearson Education, Inc. All rights reserved. 72 Outline SquareRootTest.cs ( 4 of 4 ) a) Calculating an integer square root c) Attempting a negative square rootd) Error message displayed b) Calculating a double square root Class SquareRootForm (Fig. 13.7 – next slide) demonstrates using our user-defined exception class Its expected input/output behavior:

73  2009 Pearson Education, Inc. All rights reserved. 73 Outline SquareRootTest.cs ( 1 of 4 )

74  2009 Pearson Education, Inc. All rights reserved. 74 Outline SquareRootTest.cs ( 2 of 4 ) If the numeric value that the user enters is negative, SquareRoot throws a NegativeNumber- Exception. SquareRoot invokes Math ’s Sqrt method. Fig. 13.7 | Demonstrating a user-defined exception class. (Part 2 of 4.)

75  2009 Pearson Education, Inc. All rights reserved. 75 Outline SquareRootTest.cs ( 3 of 4 ) Catching and handling a NegativeNumber­ Exception. Fig. 13.7 | Demonstrating a user-defined exception class. (Part 3 of 4.)

76  2009 Pearson Education, Inc. All rights reserved. 76 Outline SquareRootTest.cs ( 4 of 4 ) a) Calculating an integer square root c) Attempting a negative square rootd) Error message displayed b) Calculating a double square root Fig. 13.7 | Demonstrating a user-defined exception class. (Part 4 of 4.)

77  2009 Pearson Education, Inc. All rights reserved. 77 Good Programming Practice 13.1 Associating each type of malfunction with an appropriately named exception class improves program clarity Software Engineering Observation 13.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 ++READ LATER++ 13.8 User-Defined Exception Classes (Cont.)

78  2009 Pearson Education, Inc. All rights reserved. The End Ch.13 (Exception Handling) 78

79  2009 Pearson Education, Inc. All rights reserved. The End Ch.13 (Exception Handling) 79

80  2009 Pearson Education, Inc. All rights reserved. 80 ** SKIP ** 11.8 (ed.1) Handling Overflows with Operators checked and unchecked In.NET, primitive data types are stored in fixed-size structure - E.g.: max. for int is 2,147,483,647 (32 bits, see p.196) Trying to assign a value > max. value causes overflow - Overflow causes program to produce incorrect result Explicit conversions between integral data types can cause overflow C# provides operators checked and unchecked to specify the validity of integer arithmetic (or to specify a fix for an invalid result) -Checked context - The CLR throws an overflowException if overflow occur during calculation -Unchecked context - The result of the overflow is truncated

81  2009 Pearson Education, Inc. All rights reserved. 81 Use a checked context when performing calculations that can result in overflow - Define exception handlers to process exception caused by overflow Example - below ** SKIP ** 11.8 Handling Overflows with Operators checked and unchecked

82  2009 Pearson Education, Inc. All rights reserved. 82 Overflow.cs 1 ** SKIP this slide ** // Fig 11.6: Overflow.cs 2 // Demonstrating operators checked and unchecked. 3 4 using System; 5 6 // demonstrates using the checked and unchecked operators 7 class Overflow 8 { 9 static void Main( string[] args ) 10 { 11 int number1 = Int32.MaxValue; // 2,147,483,647 12 int number2 = Int32.MaxValue; // 2,147,483,647 13 int sum = 0; 14 15 Console.WriteLine( 16 "number1: {0}\nnumber2: {1}", number1, number2 ); 17 18 // calculate sum of number1 and number2 19 try 20 { 21 Console.WriteLine( 22 "\nSum integers in checked context:" ); 23 24 sum = checked( number1 + number2 ); 25 } 26 27 // catch overflow exception 28 catch ( OverflowException overflowException ) 29 { 30 Console.WriteLine( overflowException.ToString() ); 31 } 32 33 Console.WriteLine( 34 "\nsum after checked operation: {0}", sum ); 35 Initialize and declare variables and assigned value to the maximum of int Sum adds number1 and number2 in a checked context Number1 and Number2 together causes an overflow, causes overflowException The catch handler gets the overflowException and prints out its string representation

83  2009 Pearson Education, Inc. All rights reserved. 83 Overflow.cs Program Output 36 ** SKIP this slide ** Console.WriteLine( 37 "\nSum integers in unchecked context:" ); 38 39 sum = unchecked( number1 + number2 ); 40 41 Console.WriteLine( 42 "sum after unchecked operation: {0}", sum ); 43 44 } // end method Main 45 46 } // end class Overflow number1: 2147483647 number2: 2147483647 Sum integers in checked context: System.OverflowException: Arithmetic operation resulted in an overflow. at Overflow.Overflow.Main(String[] args) in f:\books\2001\csphtp1\csphtp1_examples\ch11\fig11_09\ overflow\overflow.cs:line 24 sum after checked operation: 0 Sum integers in unchecked context: sum after unchecked operation: -2 Addition of number1 and number2 in unchecked context Sum of the numbers in an unchecked context (bec. the overflowing part is truncated)


Download ppt " 2009 Pearson Education, Inc. All rights reserved. 1 13 Exception Handling Many slides modified by Prof. L. Lilien (even many without explicit message)."

Similar presentations


Ads by Google