Junior — Middle
In what situations and how do you use the try-catch block in code for exception handling?
sobes.tech AI
Answer from AI
The try-catch block is used for handling exceptions that may occur during program execution to prevent crashes and respond appropriately to errors.
When to use:
- When working with operations that may throw exceptions (e.g., file handling, network, database).
- When you need to handle an error and continue program execution.
- For logging errors or informing the user.
How to use:
try
{
// Code that may throw an exception
int result = 10 / divisor; // if divisor = 0, an exception will occur
}
catch (DivideByZeroException ex)
{
// Handling specific exception
Console.WriteLine("Division by zero is not possible.");
}
catch (Exception ex)
{
// Handling all other exceptions
Console.WriteLine("An error occurred: " + ex.Message);
}
finally
{
// Code that will run in any case
Console.WriteLine("Operation completed.");
}
Tips:
- Do not use
try-catchfor controlling program logic, only for handling truly exceptional situations. - Handle specific exceptions to avoid hiding other errors.
- Use
finallyto release resources if needed.