考虑到以下简单示例,我需要一些关于“终极”方法的帮助:
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);
}
}
答案 0 :(得分:1)
finally
执行它听起来应该的样子,它始终运行,无论是否有异常,甚至处理异常的异常。它主要用于确保正确清理共享或系统资源。
bool successful = true;
try{
// Do Some Work
Foo();
} catch {
successful = false;
throw;
} finally {
if(successful){
Console.WriteLine("Success");
}else {
Console.WriteLine("Unsuccessful");
}
}