try / catch / finally
try, catch, and finally are a safety net: try something risky, catch the problem if it falls, and finally clean up no matter what. It keeps your program from crashing.
In this page:
Syntax
try
{
// code that might throw
}
catch (ExceptionType ex)
{
// handle the error
}
finally
{
// always runs
}
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Catching
Exceptionand leaving the catch block empty, which hides real errors. - Putting a general
catch (Exception)before specific catches, which is a compile error. - Putting code that must always run in the
tryinstead offinally.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: