Title: Exception
113
2- And live the purer with the other half.
- William Shakespeare
- If theyre running and they dont look where
theyre going I have to come out from somewhere
and catch them. - J. D. Salinger
3- And oftentimes excusing of a fault
- Doth make the fault the worse by the excuse.
- William Shakespeare
- O infinite virtue! comst thou smiling from the
worlds great snare uncaught? - William Shakespeare
4OBJECTIVES
- 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- 13.1 Introduction
- 13.2 Exception Handling Overview
- 13.3 Example Divide by Zero without Exception
Handling - 13.4 Example Handling DivideByZeroExceptions
and FormatExceptions - 13.5 .NET Exception Hierarchy
- 13.6 finally Block
- 13.7 Exception Properties
- 13.8 User-Defined Exception Classes
613.1 Introduction
- An exception is an indication of a problem that
occurs during a programs execution. - Exception handling enables applications to
resolve exceptions. - Exception handling enables clear, robust and
morefault-tolerant programs.
Error-Prevention Tip 13.1 Exception handling
helps improve a programsfault tolerance.
713.2 Exception Handling Overview
- Consider the following pseudocode
- Perform a task
- If the preceding task did not execute
correctly Perform error processingPerform next
task - If the preceding task did not execute
correctly Perform error processing - In this pseudocode, we begin by performing a
task then we test whether that task executed
correctly. If not, we perform error processing.
813.2 Exception Handling Overview (Cont.)
- Exception handling enables programmers to
removeerror-handling code from the main line
of the programs execution. - Programmers can decide to handle all exceptions,
all exceptions of a certain type or all
exceptions of related types. - Such flexibility reduces the likelihood that
errors will be overlooked.
9Outline
- Figure 13.1s application divides one input
integer by a second to obtain an int result. - In this example, well see that an exception is
thrown when a method detects a problem.
DivideByZeroNoExceptionHandling.cs ( 1 of 3 )
Converting values can cause a FormatException.
Converting values can cause a FormatException.
Fig. 13.1 Integer division without exception
handling. (Part 1 of 3.)
10Outline
DivideByZeroNoExceptionHandling.cs ( 2 of 3 )
Division can cause a DivideByZeroException.
Fig. 13.1 Integer division without exception
handling. (Part 2 of 3.)
11Outline
DivideByZeroNoExceptionHandling.cs ( 3 of 3 )
Fig. 13.1 Integer division without exception
handling. (Part 3 of 3.)
1213.3 Example Divide by Zero without Exception
Handling
- If you run using Debug gt Start Debugging, the
program pauses at the line where an exception
occurs. - Try executing the application from a Command
Prompt window. - 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 in the Command Prompt.
1313.3 Example Divide by Zero without Exception
Handling (Cont.)
- Additional informationknown as a stack
tracedisplays 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.
1413.3 Example Divide by Zero without Exception
Handling (Cont.)
- A FormatException occurs when Convert method
ToInt32 receives a string that does not represent
a valid integer. - 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.
15Outline
- This application (Fig. 13.2) uses exception
handling to process DivideByZeroExceptions and
FormatExceptions. - This program demonstrates how to catch and handle
(i.e., deal with) such exceptions.
DivideByZeroTest.cs ( 1 of 4 )
Fig. 13.2 FormatException and
DivideByZeroException handlers. (Part 1 of 4.)
16Outline
DivideByZeroTest.cs ( 2 of 4 )
Fig. 13.2 FormatException and
DivideByZeroException handlers. (Part 2 of 4.)
17Outline
DivideByZeroTest.cs ( 3 of 4 )
This block catches and handles a FormatException.
This block catches and handles a
DivideBy-ZeroException.
Fig. 13.2 FormatException and
DivideByZeroException handlers. (Part 3 of 4.)
18a) Performing integer division
Outline
DivideByZeroTest.cs ( 4 of 4 )
b) Dividing by zero
c) Error message
d) Entering a string value
e) Error message
Fig. 13.2 FormatException and
DivideByZeroExceptionhandlers. (Part 3 of 4.)
1913.4 Example Handling DivideByZeroExceptions and
FormatExceptions
- The Int32.TryParse method converts a string to an
int value if possible. - The method requires two argumentsone is the
string to parse and the other is the variable in
which the converted value is to be stored. - The method returns true if the string was parsed
successfully. - If the string could not be converted, the value 0
is assigned to the second argument.
2013.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.
2113.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 specifies 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.
2213.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. - If you run the application from Visual Studio
with debugging, a window called the Exception
Assistant (Fig. 13.3) appears.
2313.4 Example Handling DivideByZeroExceptions and
FormatExceptions (Cont.)
Throw point
Exception Assistant
Fig. 13.3 Exception Assistant.
2413.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 - 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
resumes after the last catch block. - This is known as the termination model of
exception handling.
2513.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 Specifying a
comma-separated list of parameters in a catch
block is a syntax error. A catch block can have
at most one parameter.
2613.5 .NET Exception Hierarchy
- In C, only objects of class Exception and its
derived classes may be thrown and caught. - Exceptions thrown in other .NET languages can be
caught with the general catch clause.
2713.5 .NET Exception Hierarchy (Cont.)
- 13.5.1 Class SystemException
- Class Exception is the base class of .NETs
exception class hierarchy. - The CLR generates SystemExceptions, derived from
class Exception, which can occur at any point
during program execution. - If a program attempts to access an out-of-range
array index, the CLR throws an exception of type
IndexOutOfRangeException. - Attempting to use a null reference causes a
NullReferenceException.
2813.5 .NET Exception Hierarchy (Cont.)
- 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 classs 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 executea possible logic
error.
2913.5 .NET Exception Hierarchy (Cont.)
- 13.5.2 Determining Which Exceptions a Method
Throws - Search for Convert.ToInt32 method in the Index
of the Visual Studio 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.
3013.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.
3113.6 finally Block
- Programs frequently request and release resources
dynamically. - Operating systems typically prevent more than one
program from manipulating a file. - Therefore, the program should close the
file(i.e., release the resource) so other
programs can use it. - If the file is not closed, a resource leak
occurs.
3213.6 finally Block (Cont.)
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.
3313.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.
3413.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, which
makes the finally block an effective mechanism
for eliminating resource leaks.
3513.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.
36Outline
- The application in Fig. 13.4 demonstrates that
the finally block always executes.
UsingExceptions.cs ( 1 of 10 )
Main invokes method DoesNotThrowException.
Main invokes method ThrowExceptionWithCatch.
Fig. 13.4 finally blocks always execute, even
when no exception occurs. (Part 1 of 8.)
37Outline
UsingExceptions.cs ( 2 of 10 )
Fig. 13.4 finally blocks always execute, even
when no exception occurs. (Part 2 of 8.)
38Outline
UsingExceptions.cs ( 3 of 10 )
Because the try block does not throw any
exceptions, the catch block is ignored.
Fig. 13.4 finally blocks always execute, even
when no exception occurs. (Part 3 of 8.)
39Outline
UsingExceptions.cs ( 4 of 10 )
The finally block always executes.
The try block throws an exception.
The catch and finally blocks execute when the
exception occurs.
Fig. 13.4 finally blocks always execute, even
when no exception occurs. (Part 4 of 8.)
40Outline
UsingExceptions.cs ( 5 of 10 )
The catch and finally blocks execute when the
exception occurs.
The try block throws an exception.
Fig. 13.4 finally blocks always execute, even
when no exception occurs. (Part 5 of 8.)
41Outline
UsingExceptions.cs ( 6 of 10 )
The finally block executes but the exception
remains uncaught until after control returns to
Main.
The try block throws an exception.
Fig. 13.4 finally blocks always execute, even
when no exception occurs. (Part 6 of 8.)
42Outline
UsingExceptions.cs ( 7 of 10 )
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.
Fig. 13.4 finally blocks always execute, even
when no exception occurs. (Part 7 of 8.)
43Fig. 13.4 finally blocks always execute, even
when no exception occurs. (Part 8 of 8.)
44Common Programming Error 13.5 It is a compilation
error if the argument of athrowan exception
objectis not of classException 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.
45Error-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 exceptionthis can
make programs difficult to read. Its 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.
4613.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()
4713.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()
4813.7 Exception Properties
- Class Exceptions properties are used to
formulate error messages indicating a caught
exception. - Property Message stores the error message
associated with an Exception object. - Property StackTrace contains a string that
represents the method-call stack.
4913.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.
5013.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.
5113.7 Exception Properties (Cont.)
- Class Exception provides 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.
52Outline
- Our next example (Fig. 13.5) demonstrates
properties of class Exception.
Properties.cs ( 1 of 5 )
Fig. 13.5 Stack unwinding and Exception class
properties. (Part 1 of 5.)
53Outline
Properties.cs ( 2 of 5 )
Outputting properties of class Exception.
Method1 and Method2 are added to the method
stack, and then unwind when they do not catch
Method3s exception.
Fig. 13.5 Stack unwinding and Exception class
properties. (Part 2 of 5.)
54Outline
Properties.cs ( 3 of 5 )
Method1 and Method2 are added to the method
stack, and then unwind when they do not catch
Method3s exception.
Method3 catches then rethrows the exception.
Fig. 13.5 Stack unwinding and Exception class
properties. (Part 3 of 5.)
55Outline
Properties.cs ( 4 of 5 )
Fig. 13.5 Stack unwinding and Exception class
properties. (Part 4 of 5.)
56Outline
Properties.cs ( 5 of 5 )
Fig. 13.5 Stack unwinding and Exception class
properties. (Part 5 of 5.)
5713.7 Exception Properties (Cont.)
- The method called most recently appears at the
top of the stack the first method (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 objects constructor to initialize the
InnerException property.
5813.8 User-Defined Exception Classes
- In some cases, you might create exception classes
specific to the problems that occur in your
programs. - User-defined exception classes should derive
directly or indirectly from class Exception of
namespace System. - Exceptions should be documented so that other
developers will know how to handle them.
5913.8 User-Defined Exception Classes (Cont.)
- User-defined exceptions 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)
6013.8 User-Defined Exception Classes (Cont.)
Good Programming Practice 13.1 Associating each
type of malfunction with an appropriately named
exception class improvesprogram
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.
61Outline
- Class NegativeNumberException (Fig. 13.6)
represents exceptions that occur when a program
performs an illegal operation on a negative
number.
NegativeNumberException.cs ( 1 of 2 )
Inheriting from class Exception.
Parameterless constructor.
Fig. 13.6 NegativeNumberException represents
exceptions caused byillegal operations performed
on negative numbers. (Part 1 of 2.)
62Outline
NegativeNumberException.cs ( 2 of 2 )
Constructor with a single argument (the Message).
Constructor with two arguments (the Message and
InnerException).
Fig. 13.6 NegativeNumberException represents
exceptions caused byillegal operations performed
on negative numbers. (Part 2 of 2.)
63Outline
- Class SquareRootForm (Fig. 13.7) demonstrates our
user-defined exception class.
SquareRootTest.cs ( 1 of 4 )
Fig. 13.7 Demonstrating a user-defined
exception class. (Part 1 of 4.)
64Outline
SquareRootTest.cs ( 2 of 4 )
If the numeric value that the user enters is
negative, SquareRoot throws a NegativeNumber-Exce
ption.
SquareRoot invokes Maths Sqrt method.
Fig. 13.7 Demonstrating a user-defined
exception class. (Part 2 of 4.)
65Outline
SquareRootTest.cs ( 3 of 4 )
Catching and handling a NegativeNumberException.
Fig. 13.7 Demonstrating a user-defined
exception class. (Part 3 of 4.)
66Outline
b) Calculating a double square root
a) Calculating an integer square root
SquareRootTest.cs ( 4 of 4 )
c) Attempting a negative square root
d) Error message displayed
Fig. 13.7 Demonstrating a user-defined
exception class. (Part 4 of 4.)