latest Post

Exception handling in C#

Exception handling in C#

Exception handling is a built-in mechanism in .NET framework to detect and handle run time errors. The .NET framework contains many standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) does not provide a mechanism to handle these anomalies, the .NET run time environment provides a default mechanism that terminates the program execution.

C# provides the three keywords try, catch and finally to do exception handling. The try block encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for doing any clean-up process.

The general form of try-catch-finally in C# is shown below.

try  

    // Statement which can cause an exception. 
} catch (Type x)  

    // Statements for handling the exception 
} finally  

    //Any cleanup code 

If any exception occurs inside the try block then the control transfers to the appropriate catch block and later to the finally block.

But in C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks.

If there is no exception occurring inside the try block then the control directly transfers to the finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto.

In C#, exceptions are nothing but objects of the type Exception. The Exception is the ultimate base class for any exceptions in C#. The C# itself provides a couple of standard exceptions. Or even the user can create their own exception classes, provided that this should inherit from either the Exception class or one of the standard derived classes of the Exception class like DivideByZeroExcpetion or ArgumentException and so on.

About Mallikarjun A

Mallikarjun A
Recommended Posts × +

0 comments:

Post a Comment