Junior
What is a try-catch construct in C#?
sobes.tech AI
Answer from AI
The try-catch construct in C# is used for exception handling. The try block contains code that potentially may throw an exception. If an exception occurs, execution moves to the catch block, where the exception can be caught and handled.
try
{
// Code that may throw an exception
int result = 10 / int.Parse("0"); // Will throw DivideByZeroException
}
catch (DivideByZeroException ex)
{
// Handling specific exception DivideByZeroException
Console.WriteLine("Division by zero error: " + ex.Message);
}
catch (FormatException ex)
{
// Handling specific exception FormatException
Console.WriteLine("Format error: " + ex.Message);
}
catch (Exception ex)
{
// Handling any other exception
Console.WriteLine("A general error occurred: " + ex.Message);
}
finally
{
// This block always executes, regardless of whether an exception was thrown.
// Used for resource cleanup.
Console.WriteLine("Finally block executed.");
}
- The
tryblock: Contains code where an exception might occur. - The
catchblock: Catches the exception. You can have multiplecatchblocks for different exception types. Thecatch (Exception ex)block catches all exception types. - The
finallyblock: An optional block that always executes, regardless of whether an exception was thrown or caught. Often used for releasing resources such as file handles or network connections.
Using try-catch allows graceful handling of unexpected errors, preventing program crashes and providing the user with more informative error messages.