Exception Handling in C#

Apr 10
07:15

2008

Atul Jindal

Atul Jindal

  • Share this article on Facebook
  • Share this article on Twitter
  • Share this article on Linkedin

It has been observed rarely that a program runs successfully at its very first attempt. Mistakes are very common while developing a program and are co...

mediaimage

It has been observed rarely that a program runs successfully at its very first attempt. Mistakes are very common while developing a program and are considered as errors. The errors can be either compile time or run time.

Compile time errors are generally syntax errors and are detected before the execution of program. Missing semicolons,Exception Handling in C# Articles Mismatch of brackets, misspelling of keywords and identifiers, bad references and improper assignments are common compile time errors. Run Time errors are occur during the execution of program. These errors do not allow the successful execution of program and sometime leads to undesired results. In modern programming, run time errors are also called exceptions. Divide by zero, invalid typecasting, invalid references, inability to access a resource are some of the run time errors. Run time errors are considered more dangerous as compared to compile time errors. These are generally due the invalid logic and rarely due to syntax.

C# provides a very efficient method to handle run time errors (Exceptions). Whenever C# compiler encounters run time error, it creates an exception object and throws it. If exception is not caught and handled, the error message is displayed and program terminates immediately. To continue the execution of program, even error has occurred the exception must be caught and handled properly. In .NET, exceptions are instances of the classes derived from System.Exception.

Exception is handling is done using- try….catch….finally syntax. We enclose the code in try block, which is likely to raise the exception, followed by catch block. The catch block catches the exception thrown and handles it. Every catch block has the code to handle the exception appropriately. At end we write the finally block- specifying the code that is always executed regardless of whether or not the exception is thrown.

try{/////code;}catch {/////exception handling code;}finally{///the code to be executed finally whether exception occurred or not;}

A single try block can have multiple catch blocks, each handles the specific exception. But only one catch block is executed for every try block, out of multiple catch blocks. When an exception is occurred, catch blocks are examined one   by one till the appropriate is found, that can handle the exception. If no particular catch block handles the exception, then only general catch block is executed.