The C# programming language allows you to catch errors that occur during execution. For example, if you try to divide a number by zero, you will get an exception thrown.

C# Exception Handling using try catch

C# exception handling uses the try, catch and final keywords to try actions that might not succeed, to handle errors.

try
{
  //process
}
catch (exception type)
{
  //catch your exception
}

finally

The code in the finally block will execute even when no Exceptions occurred. That means if you write a final block, the code will execute after executing the try block or catch block.

try
{
  //your process here
}
Catch (exception type)
{
  //catch if the exception occurred
}
finally
{
  //alway execute
}

For example if you try to divide a number by zero.

try
{
    int val = 5;
    int div = 0;
    int result;
    result = (val / div);
    MessageBox.Show($"The result is: {result}");
}
catch (Exception  ex)
{
    MessageBox.Show($"Exception: {ex.Message}");
}
finally
{
    MessageBox.Show("Always run the finally block.");
}

How to throw Exception

The exception object will describe an error that is created and then thrown with the throw keyword. By using the throw statement inside the catch, we can catch the exception result.