C# Exception Handling With Examples

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

Exception Handling in C# is a process to handle runtime errors. The.NET framework provides a number of built-in classes for dealing with common exceptions that can result in program termination.

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.

Exception Classes in C#

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

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


Exception handling is required to maintain an application’s normal flow.

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.

Try Catch Finally in C#

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

      • try
      • catch
      • finally, and
      • throw
KeywordDescription
1. 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.
2. catch The 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, the catch block is not allowed.
3. 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.
4. throwIn C #, the 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 Finally in C#

Syntax

The syntax to use try/catch and finally blocks is as follows:

 // 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. To handle different types of exceptions in different scenarios, we can use multiple catch blocks.

Example – Exception Classes C#

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

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
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 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 always be used for normal program flow instead of conditional handling, because it is difficult for programmers 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#

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
1. MessageThe message is a virtual property of string type that provides details about the cause of the current exception.
2. 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.
3. 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.
4. 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.
5. HelpLinkThe HelpLink property is of string type that is used to hold a link (URL) to an associated help file for the error.
6. TargetSiteTargetSite is of type System.Reflection.MethodBase is used to get the method that throws the current exception.
7.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.
8. 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.
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.

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

Recommended Articles

    1. 10 Difference between interface and abstract class In C#
    2. C# Monitor class in multithreading with examples
    3. C# Enum | How To Play With Enum in C#?
    4. C# extension methods with examples
    5. Properties In C# with examples
    6. Generic Delegates in C# With Examples
    7. Constructors in C# with Examples
    8. C# Dictionary with Examples
    9. Access Modifiers in C#

One Reply to “C# Exception Handling With Examples”

Leave a Reply