Exception (C#)

An exception is an error that occurs while a C# program is running, such as dividing by zero or accessing a missing key. If not handled, it stops the program and prints an error.

C#

Exceptions are objects that derive from the System.Exception class. Common types include NullReferenceException, FormatException, IndexOutOfRangeException, and DivideByZeroException.

You handle exceptions with try/catch so your program can recover gracefully, and you can throw your own with the throw keyword.

Examples

C#

try
{
    int x = int.Parse("abc");
}
catch (FormatException)
{
    Console.WriteLine("not a number");
}

Output:

not a number

Learn it in a lesson

See also

Back to the Dictionary