Exception Handling in C#| Use of try, catch and finally block

In this article, we will talk about the exceptions and exceptions handling in C#. So, let’s discuss about the exceptions and how the .NET framework provides different keywords (try, catch, finally, and throw) to handle them.

exception handling in C#
C# Exceptions

What is an Exception?

Exceptions are a type of runtime error that disrupts the normal flow of the program. In other words, the exception is an abnormal condition that causes the termination of a running program. If the exception goes unhandled, the application might crash.

There are many exception classes available in C# such as:

 NullReferenceException  ,  ArgumentException  ,  FormatException  ,  FileNotFoundException  ,  IndexOutOfRangeException  ,  ArithmeticException  ,etc.


To maintain the normal flow of an application, exception handling is needed.

What Is Exception Handling in C#?

In C#, Exception handling is a mechanism to handle errors that occur during the execution of a program.

Exception handling ensures that the flow of the program shouldn’t break when an exception occurs.

Exceptions in the program can occur because of multiple reasons such as the wrong input, coding errors made by the programmer, system errors, or other unpredicted things.
In C#, the exception handling is done by implementing the keywords try, catch, finally, and throw.

The Exception ( System.Exception ) class is the base class of all exceptions in C#.

In C#, Exceptions allow an application to transfer the flow of control from one part of the code to another. When an exception is thrown in an application, the current execution of the code is interrupted and handed back to a parent try-catch block.

C# try, catch, finally and throw blocks

Keyword Description
tryThe try keyword identifies a block of code that might throw an exception at the run time. Once an exception occurs in the try block, the flow of control jumps to the catch block to handle those exceptions.
catchThe catch block is an exception handler block. The code in the catch block gets executed once an error occurred in the try block. The catch block can be used to write the logs and display the user-friendly error messages.
Note: The try and catch keywords come in pairs. The catch block is not allowed without the try block.
finallyThe finally block is always executed after the try/catch block whether the exception occurs or not. Finally block is used when we must want a set of code to be executed. For example, To release resources, disposing of an object, close the connection string and the files opened in the try block.
throwIn C#, the throw keyword allows raising an exception manually or programmatically. It helps to create a custom error message.
All the exceptions derived from the Exception (System.Exception) class can be raised using the throw keyword.

Syntax of handling errors in C#

In the following syntax the try, catch, and finally blocks are used to handle errors in C#.

 // try block
try
{
 // statements that may cause exception
}
 // catch block
catch (Exception ex)
{
 // exception handling
 // write logs
}
 // finally block
finally
{  
 // statements to be executed
 // Instructions to clean up resources
 // or dispose objects
}

In the above code, A try block is used to encapsulate a region of code that might generate an exception.

We can write multiple catch blocks to handle different types of exceptions in different situations.

C# Exception Handling using try, catch and finally Block

In the following example, let’s try to divide a number by zero.

Example – DivideByZeroException Class In C#

The  System.DivideByZeroException  is a class that indicates that a statement attempted to dividing a dividend with zero.

DivideByZeroException derives from the ArithmeticException that doesn’t have a catch block explicitly defined to handle the DivideByZeroException errors.

 static void Main(string[] args)
        {
            try
            {
                int number = 10;
                int div = 0;
                int result;
                result = (number / div); // Exception will occur
                Console.WriteLine($"The result of {number}/{div} is : {result}");
            }

            catch(DivideByZeroException exception)
            {
                Console.WriteLine($"Exception: {exception.Message}");
            }
            catch (Exception exception)
            {
                Console.WriteLine($"Exception: {exception.Message}");
            }

            finally 
            {
                Console.WriteLine("Enter finally block ");
            }

            Console.ReadKey();
        }
DivideByZeroException exception-shekh ali

throw keyword in C#

The throw keyword in C# can be used to raise an exception of any type whenever needed.

The following are the two main use of the throw keyword.

      • Raise an exception manually: Sometimes we might need to raise a new exception like  ArgumentException()  to the user for bad user input, or if we have an unimplemented method and we don’t want anyone to use it, then we can write throw new  InvalidOperationException()  from the try block.
      • Re-throw an exception from catch block: Sometimes we might want to catch an exception, log the error, and then re-throw it back to the parent try/catch block to handle it.
try
{
 // statements that may cause exception
}
 catch
{
  throw ;
}

//Or

try
{
 // statements that may cause exception
}
catch (Exception exception)
{
  throw new Exception("Custom Exception Message", exception);
}

We should throw exceptions only when an unexpected or invalid activity occurs in the program that prevents a method from being executing.

Exception handling should not be used every time for normal program flow instead of conditional processing because it will be hard for a programmer to maintain the code.

using System;

namespace ExceptionHandling
{
    class BankAccount
    {
        public string FirstName { get; private set; }
        public string LastName { get; private set; }
        public decimal Balance { get; private set; }

        public BankAccount(string firstName, string lastName, decimal amount)
        {

            if (string.IsNullOrEmpty(firstName))
            {
                throw new ArgumentException("FirstName cannot be empty");
            }
            if (string.IsNullOrEmpty(lastName))
            {
                throw new ArgumentException("LastName cannot be empty");
            }

            this.FirstName = firstName;
            this.LastName = lastName;
            this.Balance = amount;

        }

        public void Withdraw(decimal amount)
        {
            if (amount < 1)
            {
                throw new ArgumentException("Input amount can't be less than 1", nameof(amount));
            }

            if (amount > Balance)
            {
                throw new InvalidOperationException("Insufficient fund in account");
            }

            Balance = Balance - amount;
        }
    }

    public  class Program
    {   

        static void Main(string[] args)
        {
           // Creating object of "BankAccount" class and
           // and passing the values in the parameterized constructor

            BankAccount account = new BankAccount("Shekh", null, 100);

            Console.ReadKey();
        }
    }
    
}
ArgumentException in c#-shekh ali
ArgumentException

The ArgumentException is thrown when a method argument receives an invalid input value (example: null value). The InvalidOperationException indicates that a user attempted to use a method when the object was not in an appropriate state.


In the below program, we can throw the InvalidOperationException type in case we want to signal to our application that the withdrawal amount is higher than the available account balance.

static void Main(string[] args)
        {
            BankAccount account = new BankAccount("Shekh", "Ali", 100);

            // Trying to withdrawal amount higher than the available account balance.
            account.Withdraw(200);

            Console.ReadKey();
        }
InvalidOperationException in c#-shekh ali
InvalidOperationException

Properties Of Exception Class In C#

Exception class is used to represent the errors that occur during the execution of an application.
The following are the useful properties of the  System.Exception  class helps to understand an exception easier.

PropertyDescription
MessageThe message is a virtual property of string type that provides details about the cause of the current exception.
SourceThe source is a property of string type that is used to gets or sets the name of the application (name of the originating assembly) that causes the error.
StackTraceThe StackTrace is a getter property of string type that shows the path where an error occurred. It is very useful in the case of debugging as it includes the source file name and program line number where an error occurred.
DataThe Data is the property of the IDictionary type that holds the collection of key-value pairs. This property helps to provide additional exception data.
HelpLinkThe HelpLink property is of string type that is used to hold a link (URL) to an associated help file for the error.
TargetSiteTargetSite is of type System.Reflection.MethodBase used to get the method that throws the current exception.
InnerExceptionInnerException is a read-only property used to get the Exception instance that caused the current exception. It is used to create and preserve a series of exceptions during exception handling.
HResultHResult is a property of integer type that is used to get or set HRESULT. It is a coded numerical value that is assigned to a specific exception.

Summary

In this article, we discussed Exception handling in C# using try, catch, and finally block.

Exception handling is a mechanism to handle errors that occur during the execution of a program.
Exception handling ensures that the flow of the program shouldn’t break when an exception occurs.
Exceptions in the program can occur because of multiple reasons such as the wrong input, coding errors made by the programmer, system errors, or other unpredicted things.
In C#, the exception handling is done by implementing the keywords try, catch, finally, and throw.

I hope you enjoyed this post and found it useful. In case you have any doubt, please post your feedback, question, or comments.
Please let me know if you like this article.

Thanks for visiting 🙂

One Reply to “Exception Handling in C#| Use of try, catch and finally block”

Leave a Reply