3. C# Code
3
Error Handling
Errors can occur at almost any stage when a program runs, and many
errors might not actually be the fault of your own application.
Using traditional techniques to manually add error-detecting code
around every statement is, time consuming, and error prone in its own
right.
You can also lose sight of the main flow of an application if each
statement requires error-handling logic to manage each possible error
that can occur at every stage.
Fortunately, C# makes it easy to separate the error-handling code
from the code that implements the primary logic of a program by
using exceptions and exception handlers.
4. C# Code
4
Error Handling
Exceptions are generated when the implicit assumptions made by
your programming logic are violated.
E.g., when a program attempts to connect to a database, it
assumes that the database server is up and running on the
network.
If the server can’t be located, an exception is generated.
It’s important that your application gracefully handles any
exceptions that may occur.
If an exception is not handled, your application will terminate.
5. C# Code
5
Error Handling
You should incorporate a systematic exception handling process in
your methods.
To facilitate this process, the .NET Framework makes use of
structured exception handling through the try, catch, and finally code
blocks.
When an exception is thrown in the try block, execution transfers to
the catch block. You can use more than one catch block to filter for
specific types of exceptions that may be thrown.
The finally block performs any clean up code that you wish to
execute.
The code in the finally block executes regardless of whether an
exception is thrown.
6. C# Code
6
Error Handling
To write exception-aware programs, you need to do two things:
Write your code within a try block (try is a C# keyword). When the code runs,
it attempts to execute all the statements in the try block, and if none of the
statements generates an exception, they all run, one after the other, to
completion. However, if an error condition occurs, execution jumps out of the
try block and into another piece of code designed to catch and handle the
exception—a catch handler.
Write one or more catch handlers (catch is another C# keyword) immediately
after the try block to handle any possible error conditions. A catch handler is
intended to capture and handle a specific type of exception. If any one of the
statements within the try block causes an error, the runtime throws an
exception. The runtime then examines the catch handlers after the try block
and transfers control directly to the first matching handler.
7. C# Error Handling
7
try & single catch
This code shows a method of a class
that tries to read from a file that does
not exist.
When the exception is thrown, it is
caught in the catch block.
A catch handler employs syntax
similar to that used by a method
parameter to specify the exception to
be caught.
In the preceding example, when a
Exception is thrown, the ex variable is
populated with an object containing
the details of the exception.
8. C# Error Handling
8
try & multiple catch
All try blocks require at least one
nested catch block.
You can use the catch block to catch
all exceptions that may occur in the try
block, or you can use it to filter
exceptions based on the type of
exception.
This enables you to dynamically
respond to different exceptions based
on the exception type.
E.g., exceptions based on the different
exceptions that could occur when
trying to read a text file from disk.
9. C# Error Handling
9
try, catch &
finally
You can nest a finally block at the end of the
try block, the use of the finally block is
optional.
The finally block is for any clean up code
that needs to occur, even if an exception is
encountered.
When the code of the try block is executed
and an exception occurs, processing will
evaluate each catch block until it finds the
appropriate catch condition.
After the catch block executes, the finally
block will execute.
If the try block executes and no exception is
encountered, the catch blocks don’t execute,
but the finally block will still get processed.
10. C# Error Handling
10
Nesting try &
catch
In some cases, you may be able to
correct an exception that occurred
and continue processing the rest of
the code in the try block.
In such case, a try-catch block could
be nested around the line of code
that would cause the exception.
After the exception is handled,
processing would return to the line
of code in the outer try-catch block
immediately after the nested try
block.
13. C# Error Handling
13
Process to
response exception
After an exception is caught, the
next step in the process is to
determine how to respond to it.
You basically have two options:
either recover from the exception
or pass the exception to the
calling procedure.
The following code demonstrates
how to recover from a
DivideByZeroException by
setting the result to zero:
14. C# Error Handling
14
Process to
response exception
An exception is passed to the calling procedure using the throw
statement.
You can wrap the exception in a new exception containing
additional information that adds relevancy to the exception.
The following code shows how to wrap a caught exception in a
new one and then pass it up the calling chain:
15. C# Error Handling
15
Process to
response exception
During code execution, when an inappropriate call is made, e.g.,
a parameter to a method has an invalid value or an parameter
passed to a method causes an exception, you can throw an
exception to inform the calling code of the violation.
16. C# Error Handling
16
Process to
response exception
You preserve the original exception by using the InnerException
property of the Exception class.
Implementing this exception management policy consistently
throughout the various methods in your application will greatly
enhance your ability to build highly maintainable, flexible, and
successful applications
17. C# Error Handling
17
.NET Framework
Exception Classes
The Common Language Runtime (CLR) has a set of built-in exception
classes.
The CLR will throw an object instance of the appropriate exception type if
an error occurs while executing code instructions.
All .NET Framework exception classes derive from the SystemException
class, which in turn derives from the Exception class.
These base classes provide functionality needed by all exception classes.
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.
18. C# Error Handling
18
.NET Framework
Exception Classes
System.Exception
System.ApplicationException
System.SystemException
o System.AccessViolationException
o System.ArgumentException
System.ArgumentNullException
System.ArgumentOutOfRangeExcepti
on
o System.FormatException
o System.IndexOutOfRangeException
o System.InvalidCastException
o System.IO.IOException
System.IO.FileNotFoundException
o System.NotImplementedException
o System.NullReferenceException
o System.OutOfMemoryException
20. Why debugging?
We need Reliable Software
Users Choose Reliability over Price
Deeper Understanding
Helps you learn & write better code in the future
C# Code
20
Debugging
“The whole key to debugging effectively is to avoid the debugger as much
as possible because that’s where you waste all your time.” [John Robbins]
“Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it.” [Brian Kernighan]
21. C# Code
21
Debugging
When to use it?
Never on self-code…..
Code you write is undoubtedly PERFECT.
Always on co-worker’s code.
Debugging Basics
What are you trying to find and fix?
Two main types of code errors
Syntax: Compiler catches most if not all of these for you.
Semantic or logical: Syntactically correct yet program may “crash and
burn” at run-time!
22. C# Code
22
Debugging –
breakpoint
Stepping through your code
Starting / Stopping
Breaking
Stepping through your application
o(F10, F11 or Toolbar buttons)
Run to a specific location
oRun To Cursor (right-click
menu)
Situations under which
breakpoints are not
feasible
Timing sensitive issues
Breakpoint triggers too
often
Live Debug not possible
Debugging production
systems
23. C# Code
23
Debugging –
breakpoint
A simple, yet effective breakpoint is extremely powerful ,and
with just that it alone, 99.46% of all bugs are solved.
What does a breakpoint tell the programmer?
The line where the breakpoint is set ;)
The values of all the relevant variables till that point of code.