8.5 Finally Block The Throw expression An exception object Must be of either class Exception or one of its derived class Customize the exception type thrown from methods 19... Co
Trang 1Chapter 8 Understanding
Structured Exception Handling
Hoang Anh Viet
VietHA@it-hut.edu.vn
Hanoi University of Technology
1
Trang 2Outline
“This chapter is to discuss how to handle runtime anomalies in your code base through the use of structured exception handling Not only will you learn about the C# keywords that allow you to handle such problems (try, catch, throw, and finally), but you will also come
to understand the distinction between application-level and level exceptions In addition, this chapter examines various tools within Visual Studio 2008 that allow you to debug the exceptions that have escaped your view.”
Programmer-Defined Exception Classes
Handling Overflows with Operators checked and unchecked
2
Trang 3 8.7 Programmer-Defined Exception Classes
8.8 Handling Overflows with Operators checked and
unchecked
3
Trang 48.1 Introduction
Definitions for three commonly used anomaly-centric
terms
Bugs: errors on the part of the programmer
User errors: Unlike bugs, user errors are typically caused by
the individual running your application, rather than by those who created it
Exceptions: Exceptions are typically regarded as runtime
anomalies that are difficult, if not impossible, to account for while programming your application.
4
Trang 58.1 Introduction
Exception handling
Create application that can handle or resolve exception
Enable clear, robust and more fault-tolerant programs
NET structured exception handling is a technique well suited to deal with runtime exceptions
However, as for the bugs and user errors that have escaped
your view, the CLR will often generate a corresponding exception that identifies the problem at hand.
5
Trang 6 8.7 Programmer-Defined Exception Classes
8.8 Handling Overflows with Operators checked and
unchecked
6
Trang 7 Process synchronous errors
Follows the termination model of exception handling
7
Trang 9 8.7 Programmer-Defined Exception Classes
8.8 Handling Overflows with Operators checked and
unchecked
9
Trang 10 Method generates a FormatException
CLR automatic detection for division by zero
Occurrence will cause a DivideByZeroException
10
Trang 11// Basics of C# exception handling.
// class demonstrates how to handle exceptions from division by zero in integer
// arithmetic and from improper numeric formatting
public class DivideByZeroTest : System.Windows.Forms.Form
{
private System.Windows.Forms.Label numeratorLabel;
private System.Windows.Forms.TextBox numeratorTextBox;
private System.Windows.Forms.Label denominatorLabel;
private System.Windows.Forms.TextBox denominatorTextBox;
private System.Windows.Forms.Button divideButton;
private System.Windows.Forms.Label outputLabel;
// required designer variable
private System.ComponentModel.Container components = null ;
Trang 12// main entry point for the application
// Visual Studio NET generated code
// obtain integers input by user and divide numerator by denominator
private void divideButton_Click(
object sender, System.EventArgs e )
// Convert.ToInt32 generates FormatException if
// argument is not an integer
int numerator = Convert.ToInt32( numeratorTextBox.Text );
int denominator = Convert.ToInt32( denominatorTextBox.Text );
DivideByZeroException thrown if denominator is zero
Will not be reached (executed) if
an exception is thrown
12
Trang 13// process invalid number format
catch ( FormatException )
{
MessageBox.Show( "You must enter two integers" ,
"Invalid Number Format" ,
MessageBoxButtons OK , MessageBoxIcon Error );
}
// user attempted to divide by zero
catch ( DivideByZeroException divideByZeroException )
{
MessageBox.Show( divideByZeroException.Message,
"Attempted to Divide by Zero" ,
MessageBoxButtons OK , MessageBoxIcon Error );
Handler uses property
Message of class Exception
Catch handler for FormatException
13
Trang 14DivideByZeroTest.cs (4/4) Program Output
When incorrect format are entered into either input fields
When attempting to diving by zero
14
Trang 15 8.7 Programmer-Defined Exception Classes
8.8 Handling Overflows with Operators checked and
unchecked
15
Trang 16 Programmer use to create data types specific to their application
Low chance of program stopping execution
Trang 17 8.7 Programmer-Defined Exception Classes
8.8 Handling Overflows with Operators checked and
unchecked
17
Trang 18 Ideal for placing resource deallocation code
Execute immediately after catch handler or try block
Must be present if no catch block is present
Is optional if more than one or more catch handler exist
18
Trang 198.5 Finally Block
The Throw expression
An exception object
Must be of either class Exception or one of its derived class
Customize the exception type thrown from methods
19
Trang 20Error-Prevention Tip
“ 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 you
inadvertently keep references to unwanted objects ”
“ 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 ”
“ 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 ”
20
Trang 21Common Programming Error
Placing the Finally block before a Catch block is
a syntax error.
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.
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.
21
Trang 22// Using finally blocks.
// entry point for application
static void Main( string [] args )
{
// Case 1: No exceptions occur in called method.
Console.WriteLine( "Calling DoesNotThrowException" );
DoesNotThrowException();
// Case 2: Exception occurs and is caught in called method.
Console.WriteLine( "\nCalling ThrowExceptionWithCatch" );
ThrowExceptionWithCatch();
// Case 3: Exception occurs, but not caught
// in called method, because no catch handlers.
Console.WriteLine( "\nCalling ThrowExceptionWithoutCatch" );
Static methods of this class
so main can invoke directly
Begin try block
22
Trang 23// process exception returned from ThrowExceptionWithoutCatch
// Case 4: Exception occurs and is caught
// in called method, then rethrown to caller.
Try block for ThrowExceptionCatchRethrow
Another static method of class UsingExceptions
Would process exception that
were thrown with no catch
handler available
23
Trang 24// throws exception and catches it locally
public static void ThrowExceptionWithCatch()
End of method, program control returns to Main
Definition for method ThrowExceptionWithCatch( )
24
Trang 25throw new Exception(
"Exception in ThrowExceptionWithCatch" );
}
// catch exception thrown in try block
catch ( Exception error )
// throws exception and does not catch it locally
public static void ThrowExceptionWithoutCatch()
Throw statement to throw
the exception object
Create a new Exception
object
Try block expires because of throw command, program control continue at the first catch
following the try block.
Using the exception object’s Message property to access the error message
Try block expires immediately because of
“throw new Exception”
Definition for method ThrowExceptionWithoutCatch ( )
No catch handlers exist so the program
control go directly to the finally block
25
Trang 26// finally executes because corresponding try executed
// unreachable code; would generate logic error
Console.WriteLine( "This will never be printed" );
} // end method ThrowExceptionWithoutCatch
// throws exception, catches it and rethrows it
public static void ThrowExceptionCatchRethrow()
// catch any exception, place in object error
catch ( Exception error )
Program control continue from throw statement to the first catch block that match with the same type
Rethrow the exception back to the calling method for further processing
26
Trang 27// finally executes because corresponding try executed
// unreachable code; would generate logic error
Console.WriteLine( "This will never be printed" );
} // end method ThrowExceptionCatchRethrow
} // end class UsingExceptions
UsingExceptions.cs (6/6) Program Output
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
Finally block reached but program control returns to first occurrence of a try block
27
Trang 28 8.7 Programmer-Defined Exception Classes
8.8 Handling Overflows with Operators checked and
unchecked
28
Trang 308.6 Exception Properties
InnerException property
“Wrap” exception objects caught in code
Then throw new exception types
30
Trang 31// Stack unwinding and Exception class properties
// call Method1, any Exception it generates will be
// caught in the catch handler that follows
// Output string representation of Exception, then
// output values of InnerException, Message,
// and StackTrace properties
catch ( Exception exception )
Main becomes first method
on the method call stack
Invoked in try block, becomes second on method call stack
When control returns from stack
unwinding, try block is expired sending exception to catch block
Catch block uses method ToString and properties Message, StackTrace and InnerException to produce output
31
Trang 32// throws an Exception containing an InnerException
public static void Method3()
Not an integer format, throws a FormatException
Try block uses Convert.ToInt32 which become the fifth and final method on stack
Method3 invoked by Method2 becomes fourth on the method on the stack
Method2 invoked by Method1 becomes third on the method on the stack
Here also, the CLR searches for a try block, but unsuccessful it terminates and unwinds from the call stack
From Method1 control is then
returned to the caller which is Main
32
Trang 33// catch FormatException and wrap it in new Exception
catch ( FormatException error )
{
throw new Exception(
"Exception occurred in Method3" , error );
}
} // end method Method3
} // end class UsingExceptions
Properties.cs (3/4) Program Output
33
exception.ToString():
System.Exception: Exception occurred in Method3 ->
System.FormatException: Input string was not in a correct format.
at System.Number.ParseInt32(String s, NumberStyles style,
After catch block execute the exception
is terminated from the method call stack
Catch handler creates an
Exception object, then throws it
First block of output shows the
Control will be returned to the
statement that invoked Method3, which is Method2
This removes Method3 from
the method-call stack
Method3 terminates, because the
exception thrown is not caught in the method body
Name of the exception class followed
by the Message property value
The next eight lines show the
string representation of the InnerException object
Output for the StackTrace for
the Exception thrown in
Method3
Trang 34System.FormatException: Input string was not in a correct format.
at System.Number.ParseInt32(String s, NumberStyles style,
Properties.cs (4/4) Program Output
These two line represent the
Message property of the exception
Trang 35 8.7 Programmer-Defined Exception Classes
8.8 Handling Overflows with Operators checked and
unchecked
35
Trang 368.7 Programmer-Defined Exception Classes
Creating customized exception types
Should derive from class ApplicationException
Should end with “Exception”
Should define three constructors
A default constructor
A constructor that receives a string argument
A constructor that takes a string argument and an Exception argument
36
Trang 37// NegativeNumberException represents exceptions caused by illegal
// operations performed on negative numbers
using System;
// NegativeNumberException represents exceptions caused by
// illegal operations performed on negative numbers
class NegativeNumberException : ApplicationException
// constructor for customizing error message
public NegativeNumberException( string message )
: base ( message )
{
}
// constructor for customizing error message and
// specifying inner exception object
public NegativeNumberException( string message, Exception inner )
: base ( message, inner )
This represent the default constructor
This is a constructor that takes
in a string argument
This is a constructor that takes
in a string argument and an
Exception argument
37
Trang 38// Demonstrating a programmer-defined exception class
// accepts input and computes the square root of that input
public class SquareRootTest : System.Windows.Forms.Form
{
private System.Windows.Forms.Label inputLabel;
private System.Windows.Forms.TextBox inputTextBox;
// Required designer variable.
private System.ComponentModel.Container components = null ;
Trang 39// main entry point for the application
// computes the square root of its parameter; throws
// NegativeNumberException if parameter is negative
public double SquareRoot( double operand )
{
// if negative operand, throw NegativeNumberException
if ( operand < 0 )
throw new NegativeNumberException(
"Square root of negative number not permitted" );
// compute the square root
return Math.Sqrt( operand );
} // end class SquareRoot
// obtain user input, convert to double and calculate square root
private void squareRootButton_Click( object sender, System.EventArgs e )
Try block invoke SqaureRoot
A FormatException occurs if
not a valid number from user
39