Try, Catch, Finally Block in c#

Try, Catch, Finally Block in c#  

In the C# programming language, the try, catch, and finally blocks are used to control or manage exception handling in multiple C# programs. Exception handling in C# is a process or mechanism that allows a C# program to detect any type of program error-specific exception generated at runtime and respond to those exceptions in a structured manner. The try, catch, and finally block structures in a C# program help to properly manage and control exceptions, protecting the C# programmer from unexpected program crashes.

Try, Catch, Finally Block in c#

Try Block in C#

The try block in C# is used to analyze a group of statements in a program’s source code that could throw any type of exception. Any program code inside a user-defined try block section is executed immediately. But if an exception is thrown in the program, the control of that exception is transferred or passed to the catch block.

Catch Block in C#.

The catch block in C# programs is used to handle and manage any type of program error exception developed or generated in the try block. C# users can define the nature of specific program error exceptions in advance to catch try block errors, and handle and manage those error exceptions accordingly. If an exception or error is thrown in a try block, the catch block will execute next. The catch block can handle and control any type of error received from the try block.

Finally block in C#.

The finally block statement in a C# program is an optional user choice over a try-catch block. The finally block executes after the try block, regardless of whether or not a specific exception or error is thrown in the current program. The finally block in C# is typically used to clean up source code actions after a try block exception, such as closing files in file handling, releasing used system resources, or resetting a system value.

Try, Catch, Finally Block Basic Syntax in C#.

try

{

// Here we write program code that might throw a user-defined program exception

}

catch (ExceptionType e)

{

// Here we write program code to handle the program exception

}

finally

{

// Here we write program code that will always execute in the program, regardless of an exception

}

Element of the Try, Catch, Finally Block.

  • Exception types in a C# program indicate the type of program error or exception the C# user is catching in the current program. For example, IOException, ArgumentNullException, etc. If C# programmers want to catch all types of program exceptions in the current program, they can use the base exception class here.

A detailed example of Try, Catch, and Finally in C#.

Here is a basic example of a detailed C# program. In which you can understand the Try, Catch, and Finally statements in a single program.

using System;

class Program

{

static void Main()

{

try

{

Console.WriteLine(“Enter any integer value – “);

int integer = Convert.ToInt32(Console.ReadLine()); // here it may be thrown an exception if the input is not an integer value

Console.WriteLine(“Enter any integer – ” + integer);

}

catch (FormatException e)

{

Console.WriteLine(“Display Error – Invalid user input. Please enter a valid integer value.”);

Console.WriteLine(e.Message); // Optional – it displays the exception message

}

finally

{

Console.WriteLine(“Statement execution completed. Finally block execute anyhow.”);

}

}

}

Try, Catch, and Finally explanation.

  • In this example, a user-defined try block attempts to convert a user-input value to an integer. If the user-defined program input is not a valid integer value, it throws a FormatException error exception.
  • At the same time, the catch block immediately catches the error exception received from the try block and prints a user-defined custom error message.
  • Finally, the finally block executes after the try and catch blocks, whether or not a program exception is generated. Generally, the finally block is useful for program exception cleanup tasks.

Handling multiple program exceptions in C#.

A C# user can define multiple catch blocks to handle or manage multiple universal program exceptions in a C# program.

using System;

class Program

{

static void Main()

{

try

{

Console.WriteLine(“Enter any integer value.”);

int integer = Convert.ToInt32(Console.ReadLine()); // Here it may throw a program integer conversion exception

int output = 20 / integer; // Here it may throw a division by zero program exception

Console.WriteLine(“The output is – ” + output);

}

catch (FormatException e)

{

Console.WriteLine(“Display Error: Invalid integer input. Please enter a valid integer value.”);

}

catch (DivideByZeroException e)

{

Console.WriteLine(“Display Error: This method cannot be divided by a zero value.”);

}

finally

{

Console.WriteLine(“All execution completed.”);

}

}

}

Handling multiple program exceptions explanation.

  • If the C# user inputs a non-numeric integer value in this program, a FormatException is caught. If the C# user inputs a 0 value, a DivideByZeroException is caught in the program.
  • Finally, the finally block always executes successfully.

Catching all exceptions in a C# program using a general exception.

If the C# user doesn’t know in advance what kind of program error exceptions might be generated, here you simply want to catch all possible program error exceptions. You can catch a generic exception in this process.

using System;

class Program

{

static void Main()

{

try

{

Console.WriteLine(“Enter a valid integer.”);

int integer = Convert.ToInt32(Console.ReadLine()); // Here it may throw a program exception

int output = 10 / integer; // Here it may throw a division by zero program exception

Console.WriteLine(“Output is – ” + output);

}

catch (Exception e) // Here it catches all program exceptions

{

Console.WriteLine(“Program exception occurred – ” + e.Message);

}

finally

{

Console.WriteLine(“Program execution completed.”);

}

}

}

}

Catching all exceptions explanation.

  • In the above program, the catch (Exception e) block in Exception catches any exception, not just a specific program error exception type.

Complete try, catch, final complete example.

using System;

namespace TryCatchFinallyBlock

{

    class Tcf

    {

        static void Main(string[] args)

        {

            Console.WriteLine(“Let Explore Try Catch Finally Block in C#”);

            try

            {

                // here it start Taking input from user side

                Console.Write(“Please Enter first integer – “);

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

                Console.Write(“Please Enter second integer – “);

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

                // here we perform Division mathematical operation

                int output = value1 / value2;

                Console.WriteLine(“Result = ” + output);

            }

            catch (DivideByZeroException excpton)

            {

                // here it Handles divide by zero error exception

                Console.WriteLine(“Display Error – integer Cannot divide by zero value.”);

                Console.WriteLine(“Information – ” + excpton.Message);

            }

            catch (FormatException excpton)

            {

                // Handles invalid input error

                Console.WriteLine(“Display Error – Please enter valid integer only.”);

                Console.WriteLine(“Information – ” + excpton.Message);

            }

            catch (Exception excpton)

            {

                // here we Handles any other unexpected error

                Console.WriteLine(“Unexpected program Error generated.”);

                Console.WriteLine(“Information – ” + excpton.Message);

            }

            finally

            {

                // here This block always executes after try catch block

                Console.WriteLine(“Finally block executed in program.”);

                Console.WriteLine(“Program terminate now.”);

            }

            Console.WriteLine(“Please Press any key to terminate…”);

            Console.ReadKey();

        }

    }

}

Try, Catch, Finally Block Summary in C#.

  • try block – The try block contains program exception source code that can throw any type of error exception in a program.
  • catch block – The catch block catches program error exceptions thrown in the try block and helps handle or manage them easily.
  • finally block – In a C# program, the finally block statement is executed after the try and catch blocks, regardless of whether any error exceptions were generated in the current program. This is a useful task for system program cleanup process activities, such as closing files, network connections, etc.

Leave a Reply