Utilizor
Contact Us

C# Exceptions

Handle runtime errors with Try...Catch.

C# Exceptions - Try..Catch

When executing C# code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.

When an error occurs, C# will normally stop and generate an error message. The technical term for this is: C# will throw an exception (throw an error).

try and catch

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

try 
{
  //  Block of code to try
}
catch (Exception e)
{
  //  Block of code to handle errors
}

Finally

The finally statement lets you execute code, after try...catch, regardless of the result:

try 
{
  ...
}
catch (Exception e)
{
  ...
}
finally
{
  // code to execute after try and catch
}

The throw keyword

The throw statement allows you to create a custom error.

Examples

Try-Catch Example

Handling an index out of range exception.

using System;

class Program
{
  static void Main(string[] args)
  {
    try
    {
      int[] myNumbers = {1, 2, 3};
      Console.WriteLine(myNumbers[10]); // Error!
    }
    catch (Exception e)
    {
      Console.WriteLine("Something went wrong.");
    }
    finally     
    {
      Console.WriteLine("The 'try catch' is finished.");
    }
  }
}