try / catch / finally
In this page:
try / catch / finally
A try block contains code that might throw an exception; a matching catch block handles it if one occurs. finally runs afterward regardless of whether an exception was thrown, making it the right place for cleanup code. Execution jumps straight from the point of the exception to the nearest matching catch.
Note: finally runs even if the try or catch block contains a return statement.
Example: try / catch / finally
using System;
class Program
{
static void Main(string[] args)
{
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]);
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Caught: " + ex.Message);
}
finally
{
Console.WriteLine("Cleanup complete");
}
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: