try / catch (C#)
try/catch is how C# handles errors. Code that might fail goes in the try block, and the catch block runs instead if an exception occurs, preventing a crash.
C#
You can catch specific exception types to react differently to different problems, and add a finally block that always runs (useful for cleanup like closing files).
Catch the exception as a variable with `catch (Exception e)` to read its .Message and learn what went wrong.
Syntax
try { ... } catch (ExceptionType e) { ... } finally { ... }Examples
C#
try
{
int[] nums = { 1, 2 };
Console.WriteLine(nums[5]);
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("index out of range");
}
finally
{
Console.WriteLine("done");
}Output:
index out of range
done