C# Exception Handling

Exception management in C# programming is a method to manage runtime errors effectively. The purpose of utilizing exception handling is to ensure the continuous operation of the application despite encountering runtime errors. This approach allows developers to detect and address errors within the code without abruptly ending the program, achieved through the implementation of try, catch, throw, and finally blocks.

Understanding Exception

An anomaly in C# refers to an unforeseen occurrence or entity that is triggered while the program is running, disrupting its usual sequence. This type of error can be managed within the program. Various scenarios can lead to exceptions, including erroneous inputs, dividing by zero, missing files, and network disruptions. Failure to address the exception results in displaying the error message and halting the program execution.

Exception Handling Keywords

In C#, there are primarily four keywords that play a crucial role in exception handling. These consist of:

The <style> element is styled with a linear gradient background and border radius for a modern look. Inside, there is an icon with a large font size and text in a smaller size for additional details.

Here, we will discuss these keywords one by one.

1) Try Block

In C#, the try block is employed to encapsulate code that may raise exceptions. If an error occurs, the program flow shifts to the catch block to manage the exception, ensuring the program continues running smoothly without crashing.

Syntax:

It has the following syntax.

Example

try

{

    // Code block that might cause an exception

}

2) Catch Block

In C#, the catch clause is employed to manage the exceptions within the code. It is triggered solely when an exception is raised in the try block, allowing for precise error handling instead of abrupt termination. Furthermore, multiple catch clauses can be utilized to address various categories of exceptions.

Syntax:

It has the following syntax.

Example

catch (Exception ex)

{

    // code block that handles errors

}

To Read More: C# try/Catch

3) Throw Block

In C#, the throw keyword is employed to generate and trigger an exception whenever an error arises within the program. This command instructs the program to halt its normal execution and proceed to the closest catch block for error management.

Syntax:

It has the following syntax.

Example

throw new ExceptionType("Error message");

4) Finally Block

In C#, the finally block is a segment of code that executes regardless of the outcome of the try and catch blocks. It is essential for performing tasks like closing files, freeing up resources, or managing object disposal.

Syntax:

It has the following syntax.

Example

finally

{

    // Code block that executes always

}

To Read More: C# Finally

C# Simple Exception Handling Example

Let's consider a basic example to showcase the implementation of exception handling in C#.

Example

Example

using System;	

class ExceptionHandling

{

    static void Main()

    {

        try //using try block

        {

            Console.Write("Enter a Positive Number: ");

            int a = Convert.ToInt32(Console.ReadLine());

            if (a < 0)

            {

                // using throw block

                throw new Exception("Negative numbers are not allowed.");  

            }

            Console.WriteLine($"Square of {a} is: {a * a}");

        }

        catch (FormatException ex)   //using catch block

        {

            Console.WriteLine("Error: Please enter a valid Number.");

        }

        catch (Exception ex)

        {

            Console.WriteLine("Exception Message: " + ex.Message);

        }

        finally   //using finally block

        {

            Console.WriteLine("Program execution finished successfully.\nFinally block always executes.");

        }

    }

}

Output:

Output

Enter a Positive Number: 15

Square of 15 is: 225

Program execution finished successfully.

Finally block always executes.

Explanation:

In this instance, we illustrate the management of exceptions employing the try, catch, throw, and finally constructs. Initially, we encapsulate the code within a try block where we request a positive numerical input; in case a negative number is entered, a bespoke exception is triggered. Subsequently, we employ the catch block to address both FormatException and generic exceptions. Finally, the finally block is utilized to guarantee the execution of concluding messages or clean-up tasks irrespective of any encountered errors.

Custom Exception in C#

In the C# coding language, a custom exception is an exception defined by the user that extends the Exception class provided by the language. It comes into play when the standard exceptions fail to accurately describe the error situation. A custom exception can derive from the exception class and is capable of specifying personalized error messages and multiple properties as needed by the application.

Syntax:

It has the following syntax:

Example

public class MyCustomExcept : Exception

{

    public MyCustomExcept() : base("custom exception") 

    { 

    }

    public MyCustomExcect(string msg) : base(msg) 

    { 

    }

    public MyCustomExcept(string msg, Exception inner) : base(msg, inner) 

    { 

    }

}

C# Custom Exception Example

Let's consider a scenario to demonstrate a user-defined exception in C#.

Example

Example

using System;

// Define a custom exception class

public class AgeResException : Exception

{	

    public AgeResException(string message) : base(message)

    {

    }

}

class C# Tutorial

{

    static void Main()

    {

        try

        {

            Console.Write("Please input your age: \n");

            int age = Convert.ToInt32(Console.ReadLine());

            // Checking age criteria for voting

            if (age < 18)

            {

                throw new AgeResException("Minimum voting age is 18 years. ");

            }	

            Console.WriteLine("You are eligible to vote.");

        }

        catch (AgeResException m)

        {

            Console.WriteLine("Exception: " + m.Message);

        }

        catch (Exception m)

        {

            Console.WriteLine("The general Error: " + m.Message);

        }

        finally

        {

            Console.WriteLine("Program execution successfully.");

        }

    }

}

Output:

Case 1:

If an age below 18 is entered, the result will display:

Example

Please input your age: 

12

Exception: Minimum voting age is 18 years. 

Program execution successfully.

Case 2:

If an age of 18 or older is inputted, the result will be:

Example

Please input your age: 

18

You are eligible to vote.

Program execution successfully.

Explanation:

In this illustration, we showcase the implementation of a personalized exception for validating age. Initially, we create a class named AgeResException to verify if the provided age is under 18 years old. If the age falls below this threshold, the bespoke exception is raised. Subsequently, we employ try-catch constructs to manage both specific and standard exceptions, with the finally block guaranteeing the presentation of a concluding message without fail.

C# Exception Class

In C#, exceptions are specified within the System.Exception class, serving as the superclass for managing runtime errors. Various standard exception classes exist in C#, a few of which are detailed below.

Exception Description
System.Exception It is used to represent the parent class in C# for all exceptions.
System.SystemException It represents all the errors that occur automatically during the run-time of the program.
DivideByZeroException It throws the run-time error when division by zero occurs.
IndexOutOfRangeException It throws the error when the array or collection index is out of range.
NullReferenceException It throws the error when trying to use the null object reference.
InvalidCastException It throws the error when an invalid type casting is performed.
OutOfMemoryException It throws the error when the system does not have enough space to continue running the program.
System.ApplicationException It is the main class for all the errors that are created by the programmer.

Exception Handling Example Using Multiple Catch Blocks in C#

Let's consider a straightforward scenario to demonstrate the implementation of exception handling with multiple catch blocks in C#.

Example

Example

using System;

class C# Tutorial

{

    static void Main()

    {

        try

        {	

            Console.Write("Please enter a number:");

            int unum = Convert.ToInt32(Console.ReadLine()); 

            int[] number= {2, 4, 6, 8};

            Console.Write("Enter an array indexing position: ");

            int ind = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine($"Value at position {ind} is: {number[ind]}"); 

        }	

        catch (FormatException)

        {

            Console.WriteLine("Please input number only.");

        }

        catch (IndexOutOfRangeException)

        {

            Console.WriteLine("Choose a valid position from the array.");

        }

        catch (Exception m)

        {

            Console.WriteLine("Unexpected error: " + m.Message);

        }

    }

}

Output:

Case 1:

If we select a legitimate value from an array index ranging from 0 to 3, the result will be:

Example

Please enter a number: 10

Enter an array indexing position: 2

Value at position 2 is: 6

Case 2:

If an out-of-bounds value (greater than 3) is selected from the array index, the result will be:

Example

Please enter a number: 5

Enter an array indexing position: 4

Choose a valid position from the array.

Case 3:

If we opt for an inappropriate value (such as alphabetic characters) from the array index, the result will be:

Example

Please enter a number: abc

Please input number only.

Explanation:

In this instance, we illustrate the implementation of multiple exception handling utilizing try-catch blocks. Initially, it requests user input for a numerical value, followed by prompting for an array index to retrieve the corresponding element. Handling of exceptions includes catching a FormatException for non-numeric inputs and an IndexOutOfRangeException for invalid array index values.

Purpose of Exception Handling in C#

There are several purposes of exception handling in the C# programming language. Some of them are as follows.

  • It is used to detect and handle the run-time errors without crashing the program.
  • It is used to maintain the flow of the program even when an expected error occurs.
  • It provides a way to catch and record errors in code, so that they can be identified, managed, and fixed without terminating the application.
  • Difference between the Errors and Exceptions in C#

There exist numerous distinctions between errors and exceptions in C#. A few of these disparities are outlined below:

Features Errors Exception
Definition Errors are caused by incorrect code written by the programmer. An exception is an event or object that occurs during the execution of the program.
Occurrence Time It is mostly a compile-time issue. It is a run-time issue.
Examples Syntax errors, missing semicolon, and undeclared variables are examples of errors. Examples of exceptions include DivideByZeroException, NullReferenceException, and IndexOutOfRangeException.
Handling It must be handled to fix their issues. It must be handled using try, catch and finally blocks to fix their issues.
Code Indication Errors indicate invalid code or a mistake in the code. Exceptions indicate the valid issue with unexceptional situations during execution.

Conclusion

In summary, C# exception management plays a crucial role in program execution by addressing runtime errors and preserving the program's intended flow. The implementation of try, catch, throw, and finally blocks enhances code reliability, thereby averting program crashes.

C# Exception Handling FAQs

1) What is the Exception in C#?

In C# coding language, an exception refers to an unforeseen occurrence or entity that emerges during program execution and disrupts its regular sequence. Typically, it occurs in scenarios such as incorrect input, attempting division by zero, inability to locate a file, or network connection failure.

2) Why do we use exception handling in C#?

Exception handling is primarily used to identify and manage runtime errors without causing the program to crash.

In C#, what are the keywords employed for exception handling?

In C#, there are mainly four keywords used in exception handling.

  • Try: It is used to write the code that might cause exceptions.
  • Catch: It is used to handle the exceptions of the code. This block only runs if there is a problem in the try block.
  • Throw: It is used to create and raise an exception when something goes wrong in your code.
  • Finally: It is a block of code that always runs, whether the condition is true or not. It is generally used to clean the resources, such as closing files, releasing database connections, or unmanaged resources.

4) Why is a custom exception in C#?

In C#, a personalized exception refers to a bespoke class created by the user, which inherits from the Exception class. Its purpose is to manage errors specific to the application.

5) Can multiple catch blocks be included following a single try block?

Yes, it is possible to employ multiple catch blocks within a singular try block to manage various categories of exceptions in the C# programming language.

For Example:

Example

try

{

    int[] myarr = {10, 20, 30};

    int p = myarr[5];  

}

catch (DivideByZeroException m)

{

    Console.WriteLine("Division by zero causes an error.");

}

catch (IndexOutOfRangeException m)

{

    Console.WriteLine("Array index is out of range");

}

catch (Exception m)

{

    Console.WriteLine("Exception: " + m.Message);

}

Input Required

This code uses input(). Please provide values below: