C# Trycatch

In the C# programming language, exception handling is performed using a try/catch statement. The try block is utilized to write the code that might cause exceptions during execution. When an error occurs, the program immediately moves to the catch block to handle the run-time error. It enables multiple catch blocks to handle the different types of exceptions, such as DivideByZeroException, NullReferenceException, and IndexOutOfRangeException.

Syntax:

It has the following syntax.

Example

try

{

    // Code inside the try block that can throw an error

}

catch (ExceptionType1 ex)

{

    // Error handling code

}

In this syntax,

  • The try block contains the code that can cause an exception.
  • The catch block is used to handle the exception if it occurs.
  • C# Simple try/catch Example

Let us take an example to illustrate the try/catch block in C#.

Example

Example

using System;

class Program

{

    static void Main()

    {

        try

        {

            int n1 = 10;

            int n2 = 0;  

            int res = n1 / n2; 

           Console.WriteLine($"The divide of two number is {res}");

        }

        catch (DivideByZeroException ex)

        {

            Console.WriteLine("Error: Cannot divide by Zero.");

        }

    }

}

Output:

Output

ERROR!

Error: Cannot divide by Zero.

Explanation:

In this example, we demonstrate the exception handling in C#. First, we have taken the two variables n1 and n2 with values 10 and 0. After that, we divide n1 by n2, which causes a DivideByZeroException. Rather than crashing the program, the catch block handles the error and shows the error message.

C# Try block

In the C# programming language , the try block is used to wrap the code that may throw an exception during the run-time of the program. The try block contains the code that may cause an error, and if an error occurs, the program immediately jumps to the catch block to handle it.

Syntax:

It has the following syntax.

Example

try

{

    // Code inside the try block that can throw an error

}

C# Catch block

In C#, the catch block is used to handle the exceptions of the code. This block executes only when an error occurs in the try block. It can also access the exception object to get the details, such as the error message and stack trace. It allows us to prevent the program from crashing and enables us to handle errors in an effective manner.

Syntax:

It has the following syntax.

Example

catch (Exception ex)

{

    // Error handling code

}

Finally block

In C#, the finally block is a code block that always runs whether the condition is true or not. It is always executed after the try and catch block. It is mainly utilized to perform cleanup operations, such as releasing resources, closing files, and disconnecting from a database.

Syntax:

It has the following syntax.

Example

try

{

    // Code that may throw an exception

}

catch (ExceptionType ex)

{

    // Handle the exception

}

finally

{

    // Code that always executes.

}

C# Simple Example of handling all exceptions:

Let us take an example of handling all exceptions in the try catch block.

Example

Example

using System;

class Division

{

    static void Main()

    {

        float S = 75, P = 0, res;

        try

        {

            if (P == 0)

                throw new Exception("Division by zero is not allowed");



            res = S / P;

            Console.WriteLine(S + " / " + P + " = " + res);

        }

        catch (Exception ex)

        {

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

        }

        finally

        {

            Console.WriteLine("Finally block executed: Cleaning up resources or finishing tasks.");

        }

    }

}

Output:

Output

Error: Division by zero is not allowed

Finally block executed: Cleaning up resources or finishing tasks.

Explanation:

In this example, we have taken a class Division, and declared two floating point numbers A and B, where A is 75 and B is 0. After that, the try block checks for division by zero and throws an exception if the divisor is 0. The catch block handles the exception and prints an error message. The finally block always executes, which ensures clean-up or final tasks are performed regardless of whether an exception occurred.

Multiple Catch block

In C#, the multiple catch block provides a powerful mechanism to handle the different types of exceptions that may occur at runtime. A single try block can be followed by several catch blocks, and every block is used to handle a specific exception type. It enables us to respond to different types of error conditions in the program according to the requirements.

Syntax:

It has the following syntax.

Example

try

{

// code that may throw an exception

}

catch

{

// Handle ExceptionType1

}

catch

{

// Handle ExceptionType2

}

catch( exception ex )

{

// Handle any other exception

}

C# Simple Example Multiple Catch block

Let us take an example to illustrate the multiple catch blocks in C#.

Example

Example

using System;

class Program

{

    static void Main()

    {

        int [] numbers = {5, 20, 35, 50, 65};

        try

        {

            Console.Write("Please input a number for your choice: \n");

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

            Console.WriteLine("The Value at index " + index + " = " + numbers[index]);

        }

        catch (IndexOutOfRangeException m)

        {

            Console.WriteLine("The index you entered is invalid. ");

        }

        catch (FormatException m)

        {

            Console.WriteLine("Please enter a valid number ");

        }

        catch (Exception m)

        {

            Console.WriteLine("An unexpected error occurs: " + m.Message);

        }

        finally

        {

            Console.WriteLine("The Program execution completed.");

        }

    }

}

Output:

It has the following output.

Case 1:

Example

Enter any number for your choice: 2

The Value at index 2 = 35

The Program finished.

Case 2:

Example

Please input a number for your choice 5

The index you entered is invalid. 

The Program finished.

Case 3:

Example

Please input a number for your choice abc

Please enter a valid number 

The Program finished.

Explanation:

In this example, we have taken an integer type array and assigned the values. After that, we take a number from the user and use it as an index to display a value from the array. If the index value is invalid, it shows an error message. If the input is not a number, it gives another error, and any other errors are also handled. In the end, it always prints that the program has finished.

C# Nested try/catch block

In the C# programming language, a nested try/catch block refers to placing one try/catch block inside another to handle errors at multiple levels. The inner try/catch handles the error that happens in the part of the code. If it does not catch an exception, the outer try/catch block can handle errors in the runtime environment.

Syntax:

It has the following syntax.

Example

try

{	

    // Code inside the try block that can throw an error

}

try

{

    // Code inside the try block that can throw an error

}

catch

{

    // Error handling code

}

catch

{

    // Error handling code

}

C# Nested try/catch Example

Let us take an example to illustrate the nested try/catch in C#.

Example

Example

using System;

class Program

{

    static void Main()

    {	

        try

        {

            Console.WriteLine("The Outer try block starts.");	

            try

            {

                Console.WriteLine("The Inner try block starts.");

                int[] n = { 100, 200, 300 };

                Console.WriteLine(n[5]); // throw IndexOutOfRangeException

                int num = 10, den = 0;

                int result = num / den; // throw DivideByZeroException

                Console.WriteLine("The Inner try block finished.");

            }

            catch ( DivideByZeroException m )

            {

                Console.WriteLine("Cannot divide by zero. ");

            }

            Console.WriteLine("The Code continues after inner try-catch.");

        }

        catch (IndexOutOfRangeException m)

        {

            Console.WriteLine("Index out of range.");

        }

        catch (Exception m)

        {

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

        }

        finally

        {

            Console.WriteLine("The Finally block has been executed.");

        }

    }

}

Output:

Output

The Outer try block starts.

The Inner try block starts.

Index out of range.

The Finally block executed.

Explanation:

In this example, we demonstrate the nested try/catch block along with a finally block in C#. Inside the inner try block, it tries to access numbers[5], which does not exist and throws an IndexOutOfException. The outer catch block deals with the IndexOutOfRangeException and shows the corresponding error message. After that, when exceptions are handled, the finally block executes, which always runs and shows the message "Finally block executed".

Conclusion

In conclusion, the try/catch block is an important feature to handle run-time errors without crashing the program. Using the try, catch, and finally blocks makes the code more reliable and prevents the crashing of the program. It enables multiple catch blocks to handle the different types of exceptions.

C# try/catch FAQs

1) Describe a try/catch block in C#?

In the C# programming language, exception handling is performed using a try/catch statement. The try block is used to write the code that might cause exceptions. When an error occurs, the program jumps to the catch block to handle the run-time error. It enables multiple catch blocks to handle the different types of exceptions.

2) Are multiple catch blocks allowed with a single try block?

Yes, we have used multiple catch blocks in a single try block in C#.

Example

try

{

    // Code that may throw exceptions

}

catch ( ArgumentNullException m )

{

    Console.WriteLine(" Null argument exception " + m.Message );

}

catch ( Exception m )

{

    Console.WriteLine(" Something went wrong " + m.Message );

}

3) Is the finally block mandatory in a try/catch block in C#?

No, the finally block is not mandatory in a try/catch block. It is the optional block in exception handling. We use it when we want some code to run always, whether exceptions occur or not.

4) Define multiple catch blocks in C#?

In C#, the multiple catch block provides a powerful mechanism for handling the different types of exceptions to handle the run-time error. Since the multiple exceptions are handled using multiple catch blocks.

Example

try

{

// code that may throw an exception

}

catch

{

// Handle ExceptionType1

}

catch

{

// Handle ExceptionType2

}

5) What happens if any catch blocks match the exceptions?

If no catch blocks match the exception type, the program will terminate, and the unhandled exceptions will be thrown to the runtime environment.

Input Required

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