C# try/catch

HTML
CSS
C#
SQL

Exception Classes in C#

C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes.
The System.ApplicationException class supports exceptions generated by application programs. Hence the exceptions defined by the programmers should derive from this class.
The System.SystemException class is the base class for all predefined system exception

The try and catch keywords come in pairs:
Syntax:
try
{
// Block of code to try
}
catch (Exception e)
{
// Block of code to handle errors
}

Consider the following example, where we create an array of three integers:
This will generate an error, because myNumbers[10] does not exist.
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]); // error!
If an error occurs, we can use try…catch to catch the error and execute some code to handle it.

C# example without try/catch

using System;
public class ExExample
{
public static void Main(string[] args)
{
int a = 10;
int b = 0;
int x = a/b;
Console.WriteLine(“Rest of the code”);
}
}

In the following example, we use the variable inside the catch block (e) together with the built-in Message property, which outputs a message that describes the exception:

Example
try
{
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}

You can also output your own error message:

Example
try
{
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine(“Something went wrong.”);
}

C# Finally

C# Finally block is used to execute important code which is to be executed whether an exception is handled or not. It must be preceded by a catch or try block.
C# finally example if exception is handled