May 23, 2024

Exception Handling in C#

This article describes about the exception handling in C#; C# exception handling; Try, Catch and Finally Blocks in C#. Summary of the article:

  • What is Exceptions?
  • C# Exception Handling
  • Syntax for Try, Catch and Finally
  • Exception Classes
  • Exception Properties

What is Exceptions?
An exception is a problem that arises during the execution time of a program. A C# exception is a response to an exceptional situation that arises while a program is running. A common example of exceptions is: when we try to divide a number by zero.

C# Exception Handling
In a program an error can occur at any statement for any reason. It may complex to check codes for all types of error. Exception handling is a part of programming. Exceptions provide a way to transfer the control of the program from one part to another. C# provides 3 built-in objects Try, Catch and finally to handle exception/errors in the code. We can handle both system-level and application-level error conditions.

Try Block
In try block we write statements that might throw up an error or an exception. It identifies a block of code for which particular exceptions will be activated.

try {
//code that might cause an error

Catch Block
Catch block catches all the errors or exceptions occurred in the try block. It used to handle the errors or exception occurred in try block. A type can be an Exception class or specific type of exceptions provided by .Net framework. In a catch block Exception class is used to catch all exception.
If we use specific exception classes like (FileNotFoundException ,DivideByZeroException, IndexOutOfRangeException, InvalidCastException, SqlException) then it will throw only that specific type of exception only. Any kind of exception is thrown like (FileNotFoundException , DivideByZeroException, IndexOutOfRangeException, InvalidCastException, SqlException) is inherit only from the class System.Exception.

catch(Type ex){
//code for handling the exception

Finally Block
Finally block is useful to clean any resource that is allocated in the try block. This block is always executed even if an exception occurred or not occurred in try block. For example: if you open a file it must be closed whether an exception is raised or not.

finally {
//statements to be executed

Notable Point
In C# both catch and finally blocks are optional. A try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks. A try block cannot exist without either catch block or finally block.

Syntax for Try, Catch and Finally Block
Syntax for try/catch:

    // Code
catch (Exception ex)
    // Code
    // Code

Exception Classes
In C# exceptions are represented by classes. All the exception classes are directly or indirectly derived from the System.Exception class. The System.ApplicationException class supports exceptions generated by application programs. The System.SystemException class supports exceptions generated by system exception.

Some of the predefined exception classes in C# derived from the Sytem.SystemException class are given bellow:

  • System.IO.IOException -Handles I/O errors.
  • System.IndexOutOfRangeException -Handles errors generated when a method refers to an array index out of range.
  • System.ArrayTypeMismatchException -Handles errors generated when type is mismatched with the array type.
  • System.NullReferenceException -Handles errors generated from deferencing a null object.
  • System.DivideByZeroException -Handles errors generated from dividing a dividend with zero.
  • System.InvalidCastException -Handles errors generated during typecasting.
  • System.OutOfMemoryException -Handles errors generated from insufficient free memory.
  • System.StackOverflowException -Handles errors generated from stack overflow.

Exception Properties
The Exception type’s properties in C# are HelpLink, Message, Source, StackTrace, TargetSite and Data. To show the exception properties write the following code in a C# console application and run. This program creates an exception by dividing by zero.

    int value = 1 / int.Parse("0");
catch (Exception ex)
    Console.WriteLine("HelpLink = {0}", ex.HelpLink);
    Console.WriteLine("Message = {0}", ex.Message);
    Console.WriteLine("Source = {0}", ex.Source);
    Console.WriteLine("StackTrace = {0}", ex.StackTrace);
    Console.WriteLine("TargetSite = {0}", ex.TargetSite);
    Console.WriteLine("Data = {0}", ex.Data);

HelpLink =
Message = Attempted to divide by zero.
Source = TestConsole
StackTrace = at TestConsole.Program.Main(String[] args) in D:\Test Projects\T
estConsole\TestConsole\Program.cs:line 16
TargetSite = Void Main(System.String[])
Data = System.Collections.ListDictionaryInternal

  • HelpLink: This is empty because it was not defined on the exception. It is a string property.
  • Message: Short description of the exception’s cause. It is a read-only string property.
  • Source: Application name. It is a string property that can be assigned to or read from.
  • StackTrace: Path through the compiled program’s method hierarchy that the exception was generated from.
  • TargetSite: Name of the method where the error occurred. It helps simplify what part of the errors is recorded.
  • Data: Data dictionary on the Exception instance. Using this we can store associative keys and values.

Rashedul Alam

I am a software engineer/architect, technology enthusiast, technology coach, blogger, travel photographer. I like to share my knowledge and technical stuff with others.

View all posts by Rashedul Alam →

2 thoughts on “Exception Handling in C#

Leave a Reply

Your email address will not be published. Required fields are marked *