Exception
Exception
C# .NET includes built-in exception classes for every possible error. The Exception
class is the base class of all the exception classes.
In the above figure, the Exception class
is the base class of the SystemException
and ApplicationException classes. The
SystemException class is the base class
for all the built-in exception classes
in .NET Framework.
The ApplicationException was recommended to be base
class for all your custom exceptions classes (The custom
exeception class should be created if non of the system
exception classes can be used and you need new exception
class for business rule violations or for other application
related errors). It was meant to differentiates between
exceptions defined by applications versus exceptions
defined by the system. However, Microsoft now
recommends to derive custom exception classes from the
Exception class rather than the ApplicationException class .
The following figure shows how the NullReferenceException is
thrown in Visual Studio debug mode when you access a null
object property at runtime.
BUILT-IN EXCEPTION CLASSES
EXCEPTION HANDLING IN C#
Exceptions in the application must be handled to prevent crashing of the
program and unexpected result, log exceptions and continue with other
functionalities. C# provides built-in support to handle the exception using
try, catch & finally blocks.
try block: Any suspected code that may raise
exceptions should be put inside a try{ } block.
During the execution, if an exception occurs, the
flow of the control jumps to the first matching
catch block.
catch block: The catch block is an exception
handler block where you can perform some action
such as logging and auditing an exception. The
catch block takes a parameter of an exception
type using which you can get the details of an
exception.
finally block: The finally block will always be
executed whether an exception raised or not.
Usually, a finally block should be used to release
resources, e.g., to close any stream or file objects
that were opened in the try block.
The following may
throw an
exception if you
enter a non-
numeric character.
TO HANDLE THE POSSIBLE EXCEPTIONS IN THE ABOVE EXAMPLE, WRAP
THE CODE INSIDE A TRY BLOCK AND HANDLE THE EXCEPTION IN THE
CATCH BLOCK, AS SHOWN BELOW.
In the above example, we wrapped this code
inside a try block. If an exception occurs inside a
try block, then the program will jump to the catch
block. Inside a catch block, we display a message
to instruct the user about his mistake, and in the
finally block, we display a message about what to
do after running a program.
A try block must be followed by catch or
finally or both blocks. The try block without a
catch or finally block will give a compile-time
error.
IDEALLY, A CATCH BLOCK SHOULD INCLUDE A PARAMETER OF A BUILT-IN
OR CUSTOM EXCEPTION CLASS TO GET AN ERROR DETAIL. THE
FOLLOWING INCLUDES THE EXCEPTION TYPE PARAMETER THAT
CATCHES ALL TYPES OF EXCEPTIONS.
EXCEPTION FILTERS