How to use the try-catch-finally structure to handle exceptions in C#?
In C#, the try-catch-finally structure can be used to handle exceptions. The try block contains the code that may cause an exception, the catch block is used to catch and handle the exception, and the finally block is used to execute code that needs to run regardless of whether an exception occurs.
Below is a simple example demonstrating how to use the try-catch-finally structure to handle exceptions.
try
{
// 可能会引发异常的代码
int x = 10;
int y = 0;
int result = x / y;
}
catch (DivideByZeroException ex)
{
// 捕获并处理特定类型的异常
Console.WriteLine("除数不能为0:" + ex.Message);
}
catch (Exception ex)
{
// 捕获并处理其他类型的异常
Console.WriteLine("发生异常:" + ex.Message);
}
finally
{
// 无论是否发生异常,都会执行的代码
Console.WriteLine("程序执行完毕");
}
In the example above, the code in the try block attempts to divide a number by 0, which would throw a DivideByZeroException. The catch block catches this exception and outputs an error message. Finally, regardless of whether an exception occurs or not, the code in the finally block will execute and output “Program completed”.