2009 Pearson Education, Inc. All rights reserved. 1 13 Exception Handling Many slides modified by Prof. L. Lilien (even many without explicit message).
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
2009 Pearson Education, Inc. All rights reserved.
1
1313
ExceptionHandling
Many slides modified by Prof. L. Lilien (even many without explicit message).
• 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
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’sfault tolerance.
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
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
2009 Pearson Education, Inc. All rights reserved.
7
13.2 Exception Handling Overview – Cont.
• Keywords for exception handling– try{ <block of code in which exceptions might occur> }
– catch (<exception_parameter>) // 1 or more following each try { <how to handle this type of exception>}Note: If no “(<exception_parameter>)”, catch handles all exception types
– finally // optional, follows catch{ <codes present here will always execute – whether exception or not> }
20 } // end class DivideByZeroNoExceptionHandling Please enter an integer numerator: 100 Please enter an integer denominator: 7 Result: 100 / 7 = 14 Please enter an integer numerator: 100 Please enter an integer denominator: 0
Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero. at DivideByZeroNoExceptionHandling.Main() in C:\examples\ch13\Fig13_01\DivideByZeroNoExceptionHandling\ DivideByZeroNoExceptionHandling\
DivideByZeroNoExceptionHandling.cs: line 16
Outline
Division can cause a DivideByZeroException.
DivideByZeroNoExceptionHandling.cs
( 2 of 2 )
Stack trace
Please enter an integer numerator: 100 Please enter an integer denominator: hello
Unhandled Exception: System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt32(String value) at DivideByZeroNoExceptionHandling.Main() in C:\examples\ch13\Fig13_01\DivideByZeroNoExceptionHandling\ DivideByZeroNoExceptionHandling\
DivideByZeroNoExceptionHandling.cs: line 13
Stack trace
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.
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
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
2009 Pearson Education, Inc. All rights reserved.
17
Outline
a) Performing integer division
b) Dividing by zero
d) Entering a string valuee) Error message
c) Error message
DivideByZeroTest.cs
( 4 of 4 )
Expected behavior of the next WF app:
2009 Pearson Education, Inc. All rights reserved.
18
1 // Fig. 13.2: DivideByZeroTest.cs
2 // FormatException and DivideByZeroException handlers.
3 using System;
4 using System.Windows.Forms;
5
6 namespace DivideByZeroTest
7 {
8 public partial class DivideByZeroTestForm : Form
9 {
10 public DivideByZeroTestForm()
11 {
12 InitializeComponent();
13 } // end constructor
14
• This Windows Forms app uses exception handling to process DivideByZeroExceptions and FormatExceptions
• This program demonstrates how to catch and handle such exceptions
Outline
DivideByZeroTest.cs
( 1 of 3 )
2009 Pearson Education, Inc. All rights reserved.
1915 // obtain 2 integers from the user
16 // and divide numerator by denominator
17 private void divideButton_Click( object sender, EventArgs e )
45 "Attempted to Divide by Zero", MessageBoxButtons.OK,
46 MessageBoxIcon.Error );
47 } // end catch
48 } // end method divideButton_Click
49 } // end class DivideByZeroTestForm
50 } // end namespace DivideByZeroTest
This catch block catches and handles a FormatException.
This catch block catches and handles a DivideBy-ZeroException.
2009 Pearson Education, Inc. All rights reserved.
20
Outline
a) Performing integer division
b) Dividing by zero
d) Entering a string valuee) Error message
c) Error message
DivideByZeroTest.cs
( 3 of 3)
Output of DivideByZeroTest program
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
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.
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.
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
2009 Pearson Education, Inc. All rights reserved.
25
++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.)
Throw point Exception Assistant
• When you run the application from Visual Studio with debugging, a window called the Exception Assistant (Fig. 13.3-below) appears.
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
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
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
2009 Pearson Education, Inc. All rights reserved.
29
++READ LATER++ 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.)
Common Programming Error 13.1Logic 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.2A catch block can have at most one parameter
Specifying a comma-separated list of parameters in a catch block is a syntax error
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 IndexOutOfRangeExceptionThrown, 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
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
- In Visual StudioThe 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.
• 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.3The 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
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
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
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 completedSlide modified by L. Lilien
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.)
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
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
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
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" );
- where 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
2009 Pearson Education, Inc. All rights reserved.
45
1 // Fig. 13.4: UsingExceptions.cs
2 // Using finally blocks.
3 // finally blocks always execute, even when no exception occurs.
4 using System;
5
6 class UsingExceptions
7 {
8 static void Main()
9 {
10 // Case 1: No exceptions occur in called method
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
2009 Pearson Education, Inc. All rights reserved.
49
82 finally
83 {
84 Console.WriteLine(
85 "finally executed in ThrowExceptionWithCatch" );
86 } // end finally
87
88 Console.WriteLine( "End of ThrowExceptionWithCatch" );
89 } // end method ThrowExceptionWithCatch
90
91 // throws exception and does not catch it locally
92 static void ThrowExceptionWithoutCatch()
93 {
94 // throw exception, but do not catch it
95 try
96 {
97 Console.WriteLine( "In ThrowExceptionWithoutCatch" );
98 throw new Exception( "Exception in ThrowExceptionWithoutCatch" );
99 } // end try
OutlineThe 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
2009 Pearson Education, Inc. All rights reserved.
50
100 finally
101 {
102 Console.WriteLine( "finally executed in " +
103 "ThrowExceptionWithoutCatch" );
104 } // end finally
105
106 // unreachable code; logic error (returns to Main right after finally)
107 Console.WriteLine( "End of ThrowExceptionWithoutCatch" );
108 } // end method ThrowExceptionWithoutCatch
109
110 // throws exception, catches it and rethrows it
111 static void ThrowExceptionCatchRethrow()
112 {
113 // try block throws exception
114 try
115 {
116 Console.WriteLine( "In ThrowExceptionCatchRethrow" );
117 throw new Exception( "Exception in ThrowExceptionCatchRethrow" );
118 } // end try
OutlineThe 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.
126 // any code placed here would be unreachable code; logic error
127 } // end catch
128 finally
129 {
130 Console.WriteLine( "finally executed in " +
131 "ThrowExceptionCatchRethrow" );
132 } // end finally
133
134 // any code placed here is never reached (returns to Main after finally)
135 Console.WriteLine( "End of ThrowExceptionCatchRethrow" );
136 } // end method ThrowExceptionCatchRethrow
137 } // end class UsingExceptions
OutlineThe 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.
2009 Pearson Education, Inc. All rights reserved.
52 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 In ThrowExceptionWithoutCatch finally executed in ThrowExceptionWithoutCatch Caught exception from ThrowExceptionWithoutCatch in Main Calling ThrowExceptionCatchRethrow In ThrowExceptionCatchRethrow Message: Exception in ThrowExceptionCatchRethrow finally executed in ThrowExceptionCatchRethrow Caught exception from ThrowExceptionCatchRethrow in Main
Outline
UsingExceptions.cs
( 8 of 8)
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.)
2009 Pearson Education, Inc. All rights reserved.
54
Error-Prevention Tip 13.4When 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.2Do 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.)
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)
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.
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)
54 throw new Exception( "Exception occurred in Method3",
55 formatExceptionParameter );
56 } // end catch
57 } // end method Method3
58 } // end class Properties
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 )
2009 Pearson Education, Inc. All rights reserved.
62
exceptionParameter.ToString: System.Exception: Exception occurred in Method3 ---> System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt32(String value) at Properties.Method3() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 49 --- End of inner exception stack trace --- at Properties.Method3() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 54 at Properties.Method2() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 40 at Properties.Method1() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 34 at Properties.Main() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 14
Outline
Properties.cs
( 4 of 5 )
exceptionParameter.Message starts and ends here (highlighted, < 1 line)
exceptionParameter.StackTrace starts here
exceptionParameter.InnerException starts here
2009 Pearson Education, Inc. All rights reserved.
63
exceptionParameter.Message: Exception occurred in Method3
exceptionParameter.StackTrace: at Properties.Method3() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 54 at Properties.Method2() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 40 at Properties.Method1() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 34 at Properties.Main() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 14
exceptionParameter.InnerException: System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt32(String value) at Properties.Method3() in C:\examples\ch13\Fig13_05\Properties\ Properties\Properties.cs:line 49
Outline
Properties.cs
( 5 of 5 )
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
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
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.
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.6When 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.
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
• 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
2 // NegativeNumberException represents exceptions caused by
3 // illegal operations performed on negative numbers.
4 using System;
5
6 namespace SquareRootTest
7 {
8 class NegativeNumberException : Exception
9 {
10 // default constructor
11 public NegativeNumberException()
12 : base( "Illegal operation for a negative number" )
13 {
14 // empty body
15 } // end default constructor
16
Outline
NegativeNumberException.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.
2009 Pearson Education, Inc. All rights reserved.
71
17 // constructor for customizing error message
18 public NegativeNumberException( string messageValue )
19 : base( messageValue )
20 {
21 // empty body
22 } // end one-argument constructor
23
24 // constructor for customizing the exception's error
25 // message and specifying the InnerException object
26 public NegativeNumberException( string messageValue,
27 Exception inner )
28 : base( messageValue, inner )
29 {
30 // empty body
31 } // end two-argument constructor
32 } // end class NegativeNumberException
33 } // end namespace SquareRootTest
Outline
Constructor with two arguments (the Message and InnerException).
NegativeNumberException.cs
( 2 of 2 )
Constructor with a single argument (the Message).
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 root d) 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:
2009 Pearson Education, Inc. All rights reserved.
73
1 // Fig. 13.7: SquareRootTest.cs
2 // Demonstrating a user-defined exception class.
3 using System;
4 using System.Windows.Forms;
5
6 namespace SquareRootTest
7 {
8 public partial class SquareRootForm : Form
9 {
10 public SquareRootForm()
11 {
12 InitializeComponent();
13 } // end constructor
14
Outline
SquareRootTest.cs
( 1 of 4 )
2009 Pearson Education, Inc. All rights reserved.
74
15 // computes square root of parameter; throws
16 // NegativeNumberException if parameter is negative
17 public double SquareRoot( double value )
18 {
19 // if negative operand, throw NegativeNumberException
20 if ( value < 0 )
21 throw new NegativeNumberException(
22 "Square root of negative number not permitted" );
23 else
24 return Math.Sqrt( value ); // compute square root
25 } // end method SquareRoot
26
27 // obtain user input, convert to double, calculate square root
28 private void squareRootButton_Click( object sender, EventArgs e )
Fig. 13.7 | Demonstrating a user-defined exception class. (Part 3 of 4.)
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 root d) Error message displayed
b) Calculating a double square root
Fig. 13.7 | Demonstrating a user-defined exception class. (Part 4 of 4.)
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