c#“finally"如何用简单的例子来编写代码
本文关键字:代码 简单 何用 finally quot | 更新日期: 2023-09-27 18:12:50
考虑以下简单示例,我需要一些关于"Finally"方法的帮助:
static void Main(string[] args)
{
int x, y;
Console.WriteLine("enter a number for x");
x = int.Parse(Console.ReadLine());
Console.WriteLine("enter a number for y");
y = int.Parse(Console.ReadLine());
try
{
Console.WriteLine(x / y);
}
catch (DivideByZeroException dz)
{
Console.WriteLine(dz.Message);
}
}
finally
做它听起来应该,它总是运行,无论是否有异常,甚至异常处理异常。它主要用于确保正确地清理共享资源或系统资源。
bool successful = true;
try{
// Do Some Work
Foo();
} catch {
successful = false;
throw;
} finally {
if(successful){
Console.WriteLine("Success");
}else {
Console.WriteLine("Unsuccessful");
}
}