Introduction to Exception Handling and Defensive Programming.
-
Upload
ashley-burke -
Category
Documents
-
view
227 -
download
0
Transcript of Introduction to Exception Handling and Defensive Programming.
Introduction to Exception Handling
and Defensive Programming
Slide 2
Defensive Programming (Introduction) Code Complete puts it nicely
It’s defensive driving. You are never sure what others will do
We defend against others by Checking for invalid inputs
Slide 3
Invalid Inputs All data from external sources should be
checked In the routines (procedures) you create,
check the input parameters too Apply an error-handling strategy when
errors are detected
Slide 4
Error Handling Strategy There is no one-size-fits-all solution
Routines can return error codes We might shut down the program entirely Log and / or display messages
Closest legal value Next valid data item
Slide 5
Exceptions Most languages work the similarly here
Java, VB, C# It’s a way a procedure can say
“Something is wrong and I don’t know what to do about it. I hope that you (caller) do.”
Slide 6
Exceptions (Best Practices) Exceptions force other parts of a
program to deal with the exception Don’t unnecessarily throw exceptions
Anticipate errors, where possible, instead Don’t throw exceptions in constructors
and destructors Use the correct level of abstraction
Slide 7
Exception Handling (Introduction) Exception - a run-time error that
occurs as a result of some abnormal condition
In Visual Studio, a dialog box appears in cases of an unhandled exception
Slide 8
Exception Handling (Key Concepts) Catching an expression or handling
an exception - when an exception occurs, statements execute to process the exception in some way
Throwing an exception - a component may generate an exception that will be caught by another component
Slide 9
The Exception Object (Introduction) Remember that everything in .NET is an
object Exceptions are no “exception”
The .NET Framework defines a class named Exception and numerous derived classes
Slide 10
The Exception Object (Members) The ToString method converts the
error message to a string The Message property stores the same
message The StackTrace property shows where
the exception occurred and the call stack This is the same call stack that we
discussed during the debugging lecture
Slide 11
Exception Handling C# C# uses the try, catch, and finally,
blocks to build structured exception handlers
Structured exception handlers are just a specialized form of a decision-making statement They are really just a form of switch
statement
Slide 12
Exception Handling Syntax (1) The try, catch, and finally, blocks
declare a structured exception handler Syntax
try Statements that could cause an exception
catch exception name Code that executes when an exception occurs in the Try block
Slide 13
Exception Handling Syntax (2) Syntax (cont)
[ catch exception name ] Code that executes when an exception occurs in the Try block
[ finally ] Statements that always execute
regardless of whether an exception occurs
Statements following exception handler
Slide 14
Exception Handling Details (1) The statements in the try block contain
statements that could cause an exception to be thrown
If an exception is thrown, the statements in a catch block execute An exception handler may have multiple catch blocks to handle different types of exceptions
Slide 15
Exception Handling Details (2) Statements in the optional finally block
always execute, regardless of whether an exception occurred.
The optional finally block typically contains statements to perform housekeeping chores such as closing files or closing database connections
name argument defines a variable to store the exception
This variable works like a block-scoped variable This is a reference type
As exception clause contains the name of the exception that the catch block should handle
Slide 16
Control Flow of Exceptions
Slide 17
Propagating Exceptions It’s possible that the currently executing
procedure has no exception handler The call stack is searched for an
“active” exception handler
Slide 18
Propagating Exceptions Illustration (VB)
Slide 19
Exception Handling Properties All exceptions share similar properties
InnerException property allows the application to store the exception that led up to the current exception
Message property contains a textual message describing the exception
Source property gets the name of the application or object that caused the exception to occur
Slide 20
Exception Handling Example A simple exception handler
int Current;
try
{
Current = System.Int32.MaxValue + 1
}
Catch (System.Exception ex)
{
MessageBox.Show("Numeric overflow")
}
Slide 21
Understanding theException Hierarchy The Exception class is hierarchical All exceptions ultimately derive from the System.Exception class
System.SystemException class contains the exceptions defined by the .NET Framework itself
System.IO namespace defines exceptions related to file handling
Organize catch blocks from most specific exception to the most general exception
Slide 22
Exception Hierarchy
Slide 23
Exception HandlingStrategy for Applications Four strategies
Ignore the exception, allowing it to propagate automatically up through the call stack
Catch the exception and handle it Catch the exception and re-throw it Divide the exception into two parts. One
part is called the inner exception, and the other is called the outer exception
Slide 24
The using Keyword (Introduction) Using works in the same way as a block scoped variable
works The variable named declared in the Using statement has
the scope of the Using block Then the block exits, the variable is destroyed along with
any resources the variable is using Example:
using SreamReader = new
StreamReader(“C:\File.txt”)
{
StringVar = sr.ReadToEnd()
}
Slide 25
The C# Preprocessor A preprocessor conditionally inserts or
omits the code compiled into the program
All preprocessor directives begin with the # character
Slide 26
The C# Preprocessor (Directives) #if, #else, #elseif are the decision-
making directive You test whether a symbol has been
defined (#define) Logical and relational operators are
supported ==, !=, &&, ||,
Use #define and #undef to define and undefine preprocessor constant
Slide 27
The C# Preprocessor (Directives) #region #endregion create collapsible
regions #warning, #error throw a compiler
warning or error
Slide 28
Define Preprocessor Constants (Example)
Slide 29
Use Preprocessor Constants (Example)
Slide 30
Slide 31
#DEBUG and #TRACE These preprocessor directives are
‘special’ They enable and disable debugging and
tracing The can be reset via the application
configuration file
When disabled, the Debug and Trace code is not compiled into the application
Slide 32
The Debug and Trace Classes Both classes work the same way
One is used to embed debugging code. The other is to used to embed logging code
Write output to Output window Really the default registered “listener”
Test conditions with Assert Create custom listeners
Slide 33
See frmPreprocessor.cs