C# Exception: C# Exception handling best practices

An exception is defined as an event that occurs during the program execution that is unexpected by the program code. Exception handling is important because it handles an unwanted exception so that your program code does not crash and remains meaningful to the user.

In this article, we will discuss the exception types and exception handling in C# using try, catch, and finally blocks.

exception handling in C#
C# Exception Handling


What is an Exception in C#?

An exception is a runtime error that interrupts the normal flow of a program. In other words, an exception is an abnormal condition that causes a running program to terminate. If the exception is not handled, the application may crash.

C# Exception Classes

The .NET framework provides a number of built-in classes for dealing with common exceptions that can result in program termination.

Following is the list of a few important exception classes available in C#, such as:

  • NullReferenceException
  • ArgumentException
  • FormatException
  • FileNotFoundException
  • IndexOutOfRangeException
  • ArithmeticException

What Is Exception Handling in C#?

C# Exception Handling is a process to handle runtime errors. 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 System.Exception class is the base class of all exceptions in C#.

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

Try Catch Finally in C#

C# exception handling is done using the following built-in keywords:

  • try
  • catch
  • finally, and
  • throw

Syntax

Following is the syntax to define try/catch and finally blocks.

 // 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 syntax, the try block is used to encapsulate areas of code that may cause exceptions. Catch blocks, on the other hand, are used to handle different types of exceptions.

KeywordsDescription
tryThe try keyword identifies a block of code that can raise an exception at runtime. When an exception occurs in the try block, the control flow switches to the catch block to manage it.
catchThe catch block is used to handle exceptions. When the try block meets an error, the catch block’s code is executed. The catch block can be used to write logs and show user-friendly error messages.
Note: The try-and-catch keywords come in pairs. If there is no try block, you will not be allowed to use the catch block.
finallyThe finally block always executes after the try/catch block, regardless of whether an exception is thrown or not. When we need to run a set of code to free up resources, delete objects, close the connection string, and close open files, we can use the finally block.
throwThe throw keyword allows you to throw exceptions manually or programmatically. It helps to create custom error messages.
All exceptions derived from the Exception class (System.Exception) can be thrown using the throw keyword.
try/catch block in c#

Example: Exception handling using try-catch block

In the following example, we will try to divide a number by zero.

The System.DivideByZeroException is a class that indicates that a statement attempted to divide 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
DivideByZeroException Class In C#

throw keyword in C#

The throw keyword in C # can be used to throw any kind of exception when 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 a 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 executed.
  • Exception handling should not always be used for normal program flow instead of conditional handling, because it is difficult for programmers to maintain the code.

Example:

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
output: 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
output: InvalidOperationException

Exception Filters

Exception filters are useful when you want to handle different types of exceptions using multiple catch blocks with different exception-type parameters.

Example: Exception Filters

using System;
namespace ExceptionHandlingExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Please enter a number to divide 100: ");

            try
            {
                int number = int.Parse(Console.ReadLine());

                int result = 100 / number;

                Console.WriteLine($"100 / {number} = {result}");
            }
            catch (DivideByZeroException ex)
            {
                Console.Write($"Cannot divide by zero. Please try again.{ex.Message}");
            }
            catch (InvalidOperationException ex)
            {
                Console.Write($"Invalid operation. Please try again. {ex.Message}");
            }
            catch (FormatException ex)
            {
                Console.Write($"Not a valid format. Please try again.{ex.Message}");
            }
            catch (Exception ex)
            {
                Console.Write($"Error occurred! Please try again.{ex.Message}");
            }
            Console.ReadLine();
        }
    }
}

Properties Of C# Exception Class

The 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
01. MessageThe message is a virtual property of string type that provides details about the cause of the current exception.
02. SourceThe source is a property of string type that is used to get or set the name of the application (name of the originating assembly) that causes the error.
03. 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.
04. 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.
05. HelpLinkThe HelpLink property is of string type that is used to hold a link (URL) to an associated help file for the error.
06. TargetSiteTargetSite is of type System.Reflection.MethodBase is used to get the method that throws the current exception.
07.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.
08. 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.
Properties of exception class in C#

Advantages of C# exception handling

The following are some of the advantages of exception handling in C#

  • We can avoid the abnormal termination of the program.
  • We can take any corrective measures that can solve the problems caused by the abnormal termination.
  • Display easy-to-use error messages so that users can resolve the provided issues within their control.

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.
It 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.

Hope you like this article and find it useful. If you have any questions, please post your comments below.

References: MSDN- Exception Handling in C#

Recommended Articles:

Shekh Ali
0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments