try catch in csharp

In C#, the try-catch block is used for exception handling. It allows the programmer to identify and handle errors that may occur during program execution.

The basic structure of a try-catch block is as follows:

main.cs
try
{
    // code that might cause an exception
}
catch(Exception ex)
{
    // code to handle the exception
}
110 chars
9 lines

In the try block, you put the code that might generate an exception. If an exception occurs, the program jumps to the catch block, where you can handle the exception.

The parameter to the catch block is an object of the Exception class. This object contains information about the exception that occurred (such as the error message, the stack trace, etc.).

Here is an example that demonstrates the use of try-catch block in C#:

main.cs
try
{
    int x = Convert.ToInt32("123abc"); // This will throw an exception
    Console.WriteLine("Value of x: " + x);
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message); // Displays the error message
}
212 chars
10 lines

In this example, the try block tries to convert the string "123abc" to an integer, which is not possible. As a result, an exception is thrown, and the program jumps to the catch block, where the error message is displayed to the console.

gistlibby LogSnag