Sunday, December 25, 2011

Exceptions in C# and .Net

Exception handling is a mechanism to handle run-time errors in .NET that would otherwise cause your software to terminate prematurely.
Programmers may define and throw an exception in the case of unexpected events. Below are some important points about the exception and exception handling mechanisms in C# and .Net
·         All exceptions in .Net are objects. The System.Exception class is the base class for all exceptions in .Net. Any method can raise or throw an exception in the case of some unexpected event during its execution using the throw keyword in C#. the throws exception can be caught or dealt within the calling method using the try…catch block.
·         The code that may throw an exception which we want to handle is put in the try block. This is called attempt to catch and exception. The code to handle the thrown exception is placed in the catch block just after the try lock. This is called catching the exception. We can define which particular class of exception we want to deal with this catch block by mentioning the name of exception after the catch keyword.
·         Multiple catch blocks can be defined for a single try block where each catch block will catch a particular class of exception.
·         The code that must always be executed after the try or try…catch block is placed in finally block, placed just after the try or try…catch blocks. This code is guaranteed to always be executed whether the exception occurs or not.
·         Since exceptions are present in .Net as classes and objects, they follow the inheritance hierarchy. This means that if you write a catch block to handle a base class exception, it will automatically handle all of its sub-class’s exceptions. Attempting to catch any of the sub-class’s exceptions explicitly after the parent class exception will cause a compile time error.
·         The finally block is optional. Exception handling requires a combination of either :-
o   Try…Catch.
o   Try…Catch…Finally.
o   Try…Finally. (if not catching the exception.)
·         If you do not catch an exception, the runtime environment (Common Language Runtime or CLR) will catch it on your behalf, causing your program to terminate.

Will post more…….Enjoy!

No comments:

Post a Comment