LockDevice()が失敗し、独自に例外をスローする可能性がある次のコードについて考えてみます。finallyブロック内から例外が発生した場合、C#ではどうなりますか?
UnlockDevice(); 試す {{ DoSomethingWithDevice(); } ついに {{ LockDevice(); //例外で失敗する可能性があります }
それがfinallyブロックになかった場合に発生するのとまったく同じことです。つまり、その時点から例外が伝播する可能性があります。必要に応じて、finally内から試行/キャッチできます。
try
{
DoSomethingWithDevice();
}
finally
{
try
{
LockDevice();
}
catch (...)
{
...
}
}
この方法はTry/Catchと呼ばれます
あなたのキャッチはどこにありますか?
UnlockDevice();
try
{
DoSomethingWithDevice();
}
catch(Exception ex)
{
// Do something with the error on DoSomethingWithDevice()
}
finally
{
try
{
LockDevice(); // can fail with an exception
}
catch (Exception ex)
{
// Do something with the error on LockDevice()
}
}