Exception Handling in C# – Part II

Introduction

In the previous post, we have covered basics of exception handling, the purpose of exception handling, types of error, list of system exceptions, and some examples of run time error.

In this post will cover ways to handle the exceptions in C#, multiple exceptions catches and writing custom exceptions below is the index:

How to handle Exception in C#

C# provides built-in support to handle the exception using try, throw, catch & finally blocks.

Let’s assume some code block may raises an exception, then we will add try catch block around that code block. So, if any exception occurs then code control can be pass to the catch block where we have pre define steps to handle those error.

Syntax:

try
{
    // code that may raise exceptions
}
catch
{
    // handle exception 
}
finally
{
    // clean-up a code
}

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 predefine some action such as logging an exception or displaying appropriate a message. The catch block needs a parameter of an exception type which will provide more details about an exception.

Finally Block:
The finally block is the block which guaranteed to be executed every time whether an exception raised or not. Usually, a finally block should be used to release resources. e.g. to dispose any object or connection objects that were opened in the try block.

Throw:
Some time we need to throw explicit exception from the code for an example user has not entered expected input then we can explicit throw some error with custom message.

Example:
Suppose we have programme which accept two integers and divide those integers.

using System;

namespace ExceptionExample
{
    public class Program
    {
        public static void Main()
        {
            try
            {
                Console.WriteLine("Enter a number:");
                var n = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine($"Enter a number to divide: {n}");
                var n1 = Convert.ToInt32(Console.ReadLine());

                var result = n / n1;

                Console.WriteLine($"Result: {result}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);

            }
            Console.ReadLine();
        }
    }
}

In above programme if any exception occurs then instead abrupt termination programme will give information about the error.

Note: catch block takes exception parameter, if program not specific it, it will consider by default exception type.
Example:

try
{
//Code
}
catch
{
// handle exception 
}

In above example as we have not specified any parameter in catch hence by default it will consider as Exception class parameter so above syntax and below syntax is the same

try
{
//Code
}
catch(Exception ex)
{
// handle exception 
}

Nesting of try and catch blocks

C# allow to added multiple nesting of try and catch blocks, so we can add multiple try catch block one inside another.

Syntax:

//Outer catch block
try
{
//Some code
//inner catch block
try
{
//Some code

}
catch
{
//Handle exception for inner try block
}
} 
catch
{
//Handle exception for outer try block

}

Finally block

The finally block is used to execute a code, whether an exception is thrown or not thrown. i.e. finally block guaranteed to be execute. so, it can be used to ensure that some logic is always executed before the method is exited. So finally block is used to releasing resource or to clean up the code

Example:
Finally block can be used for closing connections, disposing objects etc.

Note: finally, blocks are optional block in try catch statements. Also, we cannot add multiple finally block to a method and not allow return, continue, or break keywords

Multiple Catch Block


In C#, You can use more than one catch block with the try block to handle different types of exceptions means each catch block is used to handle different type of exception.

Custom Exception or user-defined exceptions

C# Provides way to create custom exception, so why we need custom exception?
Many times, while programming we need to raise an exception when some condition fails, or some validation fails to raise this kind of exception we need to create a custom exception.

Lets understand this by an example:

So, we have an ecommerce site which allow user to apply promo code. user can use the promo code only once

namespace Resource
{
    public class Customer
    {
        public string CustomerId { get; set; }
        public string CustomerName { get; set; }
        public bool IsPromoCodeUsed { get; set; }
    }
}

Here is custom exception class

 System;

namespace Ecommerce
{
    [Serializable]
    public class PromoCodeException : Exception
    {
        public PromoCodeException()
        {

        }

        public PromoCodeException(string customerName)
            : base($"Promo Code already used by: {customerName}")
        {

        }
    }
}

Now, if let’s say customer already avail the promo code and he is trying to apply promo code then its breaking our rule and you can throw PromoCodeException

using System;
using System.IO;
using Ecommerce;
using Resource;

namespace ExceptionExample
{
    class Program
    {
        static void Main()
        {
            try
            {
                var customer = GetCustomerDetailByCustomerId("cus0012");

                if (customer.IsPromoCodeUsed)
                    throw new PromoCodeException();
            }
            catch (PromoCodeException e)
            {
                Console.WriteLine(e);
                throw;
            }
            catch
            {
                Console.WriteLine("Exception");
                throw;
            }
        }

        private static Customer GetCustomerDetailByCustomerId(string customerId)
        {
         return new Customer()
         {
             CustomerId = customerId,
             CustomerName = "Mahesh",
             IsPromoCodeUsed =true
         };
        }
    }
}

Here is more detail about Multiple Catch Block & Interview Question Related to Multiple Catch Block in C#

Leave a Reply

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