1
2006 Pearson Education, Inc. All rights reserved.
1212
Exception Handling
2
2006 Pearson Education, Inc. All rights reserved.
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
3
2006 Pearson Education, Inc. All rights reserved.
And oftentimes excusing of a faultDoth 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
4
2006 Pearson Education, Inc. All rights reserved.
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.
5
2006 Pearson Education, Inc. All rights reserved.
12.1 Introduction
12.2 Exception Handling Overview
12.3 Example: Divide by Zero Without Exception Handling
12.4 Example: Handling DivideByZeroExceptions and FormatExceptions
12.4.1 Enclosing Code in a try Block
12.4.2 Catching Exceptions
12.4.3 Uncaught Exceptions
12.4.4 Termination Model of Exception Handling
12.4.5 Flow of Control When Exceptions Occur
12.5 .NET Exception Hierarchy
12.5.1 Classes ApplicationException and SystemException
12.5.2 Determining Which Exceptions a Method Throws
12.6 finally Block
12.7 Exception Properties
12.8 User-Defined Exception Classes
12.9 Wrap-Up
6
2006 Pearson Education, Inc. All rights reserved.
12.1 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
7
2006 Pearson Education, Inc. All rights reserved.
Error-Prevention Tip 12.1
Exception handling helps improve a program’s fault tolerance.
8
2006 Pearson Education, Inc. All rights reserved.
12.2 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
9
2006 Pearson Education, Inc. All rights reserved.
12.3 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
10
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 12.1: DivideByZeroNoExceptionHandling.cs
2 // An application that attempts to divide by zero.
3 using System;
4
5 class DivideByZeroNoExceptionHandling
6 {
7 static void Main()
8 {
9 // get numerator and denominator
10 Console.Write( "Please enter an integer numerator: " );
11 int numerator = Convert.ToInt32( Console.ReadLine() );
12 Console.Write( "Please enter an integer denominator: " );
13 int denominator = Convert.ToInt32( Console.ReadLine() );
14
15 // divide the two integers, then display the result
16 int result = numerator / denominator;
17 Console.WriteLine( "\nResult: {0:D} / {1:D} = {2:D}",
18 numerator, denominator, result );
19 } // end Main
20 } // end class DivideByZeroNoExceptionHandling
Outline
DivideByZeroNoExceptionHandling.cs
(1 of 2)
Take and assign inputs from user
Divide numerator by denominator
11
2006 Pearson Education, Inc. All rights reserved.
Outline
DivideByZeroNoExceptionHandling.cs
(2 of 2)
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\ch12\Fig12_01\DivideByZeroNoExceptionHandling\ DivideByZeroNoExceptionHandling.cs:line16
Please enter an integer numerator: 100
Please enter an integer denominator: hello
Unhandled Exception: System.FormatException: Attempted to divide by zero. 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\ch12\Fig12_01\DivideByZeroNoExceptionHandling\ DivideByZeroNoExceptionHandling.cs: line13
Exception: division by zero!
Exception: denominator is not even a number!
12
2006 Pearson Education, Inc. All rights reserved.
12.4 Example: Handling DivideByZeroExceptions and FormatExceptions
• With exception handling, the program catches and handles (i.e., deals with) the exception
• Fig. 12.2 displays error message and allows user to enter another set of values
13
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 12.2: DivideByZeroTest.cs
2 // Exception handlers for FormatException and DivideByZeroException.
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
15 // obtain 2 integers from the user
16 // and divide numerator by denominator
17 private void DivideButton_Click( object sender, EventArgs e )
18 {
19 OutputLabel.Text = ""; // clear Label OutputLabel
20
Outline
DivideByZeroTest.cs
(1 of 3)
14
2006 Pearson Education, Inc. All rights reserved.
21 // retrieve user input and calculate quotient
22 try
23 {
24 // Convert.ToInt32 generates FormatException
25 // if argument is not an integer
26 int numerator = Convert.ToInt32( NumeratorTextBox.Text );
27 int denominator = Convert.ToInt32( DenominatorTextBox.Text );
28
29 // division generates DivideByZeroException
30 // if denominator is 0
31 int result = numerator / denominator;
32
33 // display result in OutputLabel
34 OutputLabel.Text = result.ToString();
35 } // end try
36 catch ( FormatException )
37 {
38 MessageBox.Show( "You must enter two integers.",
39 "Invalid Number Format", MessageBoxButtons.OK,
40 MessageBoxIcon.Error );
41 } // end catch
42 catch ( DivideByZeroException divideByZeroExceptionParameter )
43 {
44 MessageBox.Show( divideByZeroExceptionParameter.Message,
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
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
15
2006 Pearson Education, Inc. All rights reserved.
Outline
DivideByZeroTest.cs
(3 of 3)
(a)
(b)
(d)
(c)
(e)
16
2006 Pearson Education, Inc. All rights reserved.
12.4.1 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
17
2006 Pearson Education, Inc. All rights reserved.
12.4.2 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
18
2006 Pearson Education, Inc. All rights reserved.
12.4.3 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
19
2006 Pearson Education, Inc. All rights reserved.
Fig. 12.3 | Exception Assistant.
Throw point Exception Assistant
20
2006 Pearson Education, Inc. All rights reserved.
12.4.4 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
21
2006 Pearson Education, Inc. All rights reserved.
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.
22
2006 Pearson Education, Inc. All rights reserved.
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.
23
2006 Pearson Education, Inc. All rights reserved.
12.5 .NET Exception Hierarchy
• In C#, only objects of class Exception and its derived classes may be thrown or caught
24
2006 Pearson Education, Inc. All rights reserved.
12.5.1 Classes ApplicationException and SystemException
• Class Exception – Can be used to catch all exceptions
• Catch blocks uses is-a relationship
– Derived Class ApplicationExceptions • Base class that programmers can extend to create exception
classes specific to their application
• Programs can recover from most ApplicationExceptions and continue execution
– Derived Class SystemException • Mainly, this exception can be avoided if coded properly
• CLR throws SystemException when it becomes unstable
25
2006 Pearson Education, Inc. All rights reserved.
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.
26
2006 Pearson Education, Inc. All rights reserved.
12.5.2 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
27
2006 Pearson Education, Inc. All rights reserved.
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.
28
2006 Pearson Education, Inc. All rights reserved.
12.6 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
29
2006 Pearson Education, Inc. All rights reserved.
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.
30
2006 Pearson Education, Inc. All rights reserved.
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.
31
2006 Pearson Education, Inc. All rights reserved.
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.
32
2006 Pearson Education, Inc. All rights reserved.
Common Programming Error 12.4
Placing the finally block before a catch block is a syntax error.
33
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 12.4: UsingExceptions.cs
2 // Using finally blocks.
3 // Demonstrate that finally always executes.
4 using System;
5
6 class UsingExceptions
7 {
8 static void Main()
9 {
10 // Case 1: No exceptions occur in called method
11 Console.WriteLine( "Calling DoesNotThrowException" );
12 DoesNotThrowException();
13
14 // Case 2: Exception occurs and is caught in called method
15 Console.WriteLine( "\nCalling ThrowExceptionWithCatch" );
16 ThrowExceptionWithCatch();
17
18 // Case 3: Exception occurs, but is not caught in called method
19 // because there is no catch block.
20 Console.WriteLine( "\nCalling ThrowExceptionWithoutCatch" );
Outline
UsingExceptions.cs
(1 of 8)
No exceptions occur
No try block needed, exception handled in method
34
2006 Pearson Education, Inc. All rights reserved.
21
22 // call ThrowExceptionWithoutCatch
23 try
24 {
25 ThrowExceptionWithoutCatch();
26 } // end try
27 catch
28 {
29 Console.WriteLine( "Caught exception from " +
30 "ThrowExceptionWithoutCatch in Main" );
31 } // end catch
32
33 // Case 4: Exception occurs and is caught in called method,
34 // then rethrown to caller.
35 Console.WriteLine( "\nCalling ThrowExceptionCatchRethrow" );
36
37 // call ThrowExceptionCatchRethrow
38 try
39 {
40 ThrowExceptionCatchRethrow();
41 } // end try
42 catch
43 {
44 Console.WriteLine( "Caught exception from " +
45 "ThrowExceptionCatchRethrow in Main" );
46 } // end catch
47 } // end method Main
Outline
UsingExceptions.cs
(2 of 8)
Exception handled outside of method
Exception handled outside of method; Exception is
rethrown
35
2006 Pearson Education, Inc. All rights reserved.
48
49 // no exceptions thrown
50 static void DoesNotThrowException()
51 {
52 // try block does not throw any exceptions
53 try
54 {
55 Console.WriteLine( "In DoesNotThrowException" );
56 } // end try
57 catch
58 {
59 Console.WriteLine( "This catch never executes" );
60 } // end catch
61 finally
62 {
63 Console.WriteLine( "finally executed in DoesNotThrowException" );
64 } // end finally
65
66 Console.WriteLine( "End of DoesNotThrowException" );
67 } // end method DoesNotThrowException
Outline
UsingExceptions.cs
(3 of 8)
The finally block executes regardless if
there is an exception or not
36
2006 Pearson Education, Inc. All rights reserved.
68
69 // throws exception and catches it locally
70 static void ThrowExceptionWithCatch()
71 {
72 // try block throws exception
73 try
74 {
75 Console.WriteLine( "In ThrowExceptionWithCatch" );
76 throw new Exception( "Exception in ThrowExceptionWithCatch" );
77 } // end try
78 catch ( Exception exceptionParameter )
79 {
80 Console.WriteLine( "Message: " + exceptionParameter.Message );
81 } // end catch
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
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
37
2006 Pearson Education, Inc. All rights reserved.
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
100 finally
101 {
102 Console.WriteLine( "finally executed in " +
103 "ThrowExceptionWithoutCatch" );
104 } // end finally
105
106 // unreachable code; logic error
107 Console.WriteLine( "End of ThrowExceptionWithoutCatch" );
108 } // end method ThrowExceptionWithoutCatch
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
38
2006 Pearson Education, Inc. All rights reserved.
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
119 catch ( Exception exceptionParameter )
120 {
121 Console.WriteLine( "Message: " + exceptionParameter.Message );
122
123 // rethrow exception for further processing
124 throw;
Outline
UsingExceptions.cs
(6 of 8)
Throw exception with personalized message
Rethrow caught exception
39
2006 Pearson Education, Inc. All rights reserved.
125
126 // 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
135 Console.WriteLine( "End of ThrowExceptionCatchRethrow" );
136 } // end method ThrowExceptionCatchRethrow
137 } // end class UsingExceptions
Outline
UsingExceptions.cs
(7 of 8)
The finally block executes regardless if
there is an exception or not
40
2006 Pearson Education, Inc. All rights reserved.
Outline
UsingExceptions.cs
(8 of 8)
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
41
2006 Pearson Education, Inc. All rights reserved.
12.6 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
42
2006 Pearson Education, Inc. All rights reserved.
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.
43
2006 Pearson Education, Inc. All rights reserved.
12.6 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
44
2006 Pearson Education, Inc. All rights reserved.
12.6 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
45
2006 Pearson Education, Inc. All rights reserved.
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.
46
2006 Pearson Education, Inc. All rights reserved.
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.
47
2006 Pearson Education, Inc. All rights reserved.
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.
48
2006 Pearson Education, Inc. All rights reserved.
12.6 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();
}
49
2006 Pearson Education, Inc. All rights reserved.
12.7 Exception Properties
•Exception Properties– Message
• Stores the error message associated with an Exception object
– StackTrace• Contains a string that represents the method-call stack
50
2006 Pearson Education, Inc. All rights reserved.
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.
51
2006 Pearson Education, Inc. All rights reserved.
12.7 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
52
2006 Pearson Education, Inc. All rights reserved.
12.7 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
53
2006 Pearson Education, Inc. All rights reserved.
12.7 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
54
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 12.5: Properties.cs
2 // Stack unwinding and Exception class properties.
3 // Demonstrates using properties Message, StackTrace and InnerException.
4 using System;
5
6 class Properties
7 {
8 static void Main()
9 {
10 // call Method1; any Exception generated is caught
11 // in the catch block that follows
12 try
13 {
14 Method1();
15 } // end try
16 catch ( Exception exceptionParameter )
17 {
18 // output the string representation of the Exception, then output
19 // properties InnerException, Message and StackTrace
20 Console.WriteLine( "exceptionParameter.ToString: \n{0}\n",
21 exceptionParameter.ToString() );
22 Console.WriteLine( "exceptionParameter.Message: \n{0}\n",
23 exceptionParameter.Message );
24 Console.WriteLine( "exceptionParameter.StackTrace: \n{0}\n",
25 exceptionParameter.StackTrace );
26 Console.WriteLine( "exceptionParameter.InnerException: \n{0}\n",
27 exceptionParameter.InnerException.ToString() );
28 } // end catch
29 } // end method Main
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
55
2006 Pearson Education, Inc. All rights reserved.
30
31 // calls Method2
32 static void Method1()
33 {
34 Method2();
35 } // end method Method1
36
37 // calls Method3
38 static void Method2()
39 {
40 Method3();
41 } // end method Method2
42
43 // throws an Exception containing an InnerException
44 static void Method3()
45 {
46 // attempt to convert string to int
47 try
48 {
49 Convert.ToInt32( "Not an integer" );
50 } // end try
51 catch ( FormatException formatExceptionParameter )
52 {
53 // wrap FormatException in new Exception
54 throw new Exception( "Exception occurred in Method3",
55 formatExceptionParameter );
56 } // end catch
57 } // end method Method3
58 } // end class Properties
Outline
Properties.cs
(2 of 4)
Call Method2()
Call Method3()
Generate exception
Rewrap and throw exception
56
2006 Pearson Education, Inc. All rights reserved.
Outline
Properties.cs
(3 of 4)
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\ch12\Fig12_04\Properties\ Properties.cs: line 49 --- End of inner exception stack trace --- at Properties.Method3() in C:\examples\ch12\Fig12_04\Properties\ Properties.cs: line 54 at Properties.Method2() in C:\examples\ch12\Fig12_04\Properties\
Properties.cs: line 40 at Properties.Method1() in C:\examples\ch12\Fig12_04\Properties\ Properties.cs: line 34 at Properties.Main() in C:\examples\ch12\Fig12_04\Properties\ Properties.cs: line 14
57
2006 Pearson Education, Inc. All rights reserved.
Outline
Properties.cs
(4 of 4)
exceptionParameter.Message: Exception occurred in Method3
exceptionParameter.StackTrace: at Properties.Method3() in C:\examples\ch12\Fig12_04\Properties\ Properties.cs: line 54 at Properties.Method2() in C:\examples\ch12\Fig12_04\Properties\ Properties.cs: line 40 at Properties.Method1() in C:\examples\ch12\Fig12_04\Properties\ Properties.cs: line 34 at Properties.Main() in C:\examples\ch12\Fig12_04\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\ch12\Fig12_04\Properties\ Properties.cs: line 49
58
2006 Pearson Education, Inc. All rights reserved.
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.
59
2006 Pearson Education, Inc. All rights reserved.
12.8 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
60
2006 Pearson Education, Inc. All rights reserved.
Good Programming Practice 12.1
Associating each type of malfunction with an appropriately named exception class improves program clarity.
61
2006 Pearson Education, Inc. All rights reserved.
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.
62
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 12.6: NegativeNumberException.cs
2 // NegativeNumberException represents exceptions caused by
3 // illegal operations performed on negative numbers.
4 using System;
5
6 namespace SquareRootTest
7 {
8 class NegativeNumberException : ApplicationException
9 {
10 // default constructor
11 public NegativeNumberException()
12 : base( "Illegal operation for a negative number" )
13 {
14 // empty body
15 } // end default constructor
16
17 // constructor for customizing error message
18 public NegativeNumberException( string messageValue )
19 : base( messageValue )
20 {
21 // empty body
22 } // end one-argument constructor
23
Outline
NegativeNumberException.cs
(1 of 2)
NegativeNumberException extends ApplicationException
Calls the base class constructor with exception message
Calls the base class constructor with a string
63
2006 Pearson Education, Inc. All rights reserved.
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
NegativeNumberException.cs
(2 of 2)
Calls the base class constructor with a string and an
Exception
64
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 12.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
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
Outline
SquareRootTest.cs
(1 of 3)
Throw user defined exception
Return square root of the argument
65
2006 Pearson Education, Inc. All rights reserved.
26
27 // obtain user input, convert to double, calculate square root
28 private void SquareRootButton_Click( object sender, EventArgs e )
29 {
30 OutputLabel.Text = ""; // clear OutputLabel
31
32 // catch any NegativeNumberException thrown
33 try
34 {
35 double result =
36 SquareRoot( Convert.ToDouble( InputTextBox.Text ) );
37
38 OutputLabel.Text = result.ToString();
39 } // end try
40 catch ( FormatException formatExceptionParameter )
41 {
42 MessageBox.Show( formatExceptionParameter.Message,
43 "Invalid Number Format", MessageBoxButtons.OK,
44 MessageBoxIcon.Error );
45 } // end catch
46 catch ( NegativeNumberException
47 negativeNumberExceptionParameter )
48 {
49 MessageBox.Show( negativeNumberExceptionParameter.Message,
50 "Invalid Operation", MessageBoxButtons.OK,
51 MessageBoxIcon.Error );
52 } // end catch
Outline
SquareRootTest.cs
(2 of 3)
Notify user of the exception
66
2006 Pearson Education, Inc. All rights reserved.
53 } // end method SquareRootButton_Click
54 } // end class SquareRootForm
55 } // end namespace SquareRootTest
Outline
SquareRootTest.cs
(3 of 3)
(a)
(c)
(b)
(d)