Try/Catch を使用する場合、エラーが検出されず、Catch がない場合に、If/Else のようにコードを実行する方法はありますか?
try
{
//Code to check
}
catch(Exception ex)
{
//Code here if an error
}
//Code that I want to run if it's all OK ??
finally
{
//Code that runs always
}
Try/Catch を使用する場合、エラーが検出されず、Catch がない場合に、If/Else のようにコードを実行する方法はありますか?
try
{
//Code to check
}
catch(Exception ex)
{
//Code here if an error
}
//Code that I want to run if it's all OK ??
finally
{
//Code that runs always
}
ブロックの最後にコードを追加しますtry
。明らかに、以前に例外がなかった場合にのみ、そこに到達します。
try {
// code to check
// code that you want to run if it's all ok
} catch {
// error
} finally {
// cleanup
}
おそらく、予想される例外のみをキャッチするように catch を変更する必要があります。これには、「問題がなければ実行したいコード」でスローされた例外が含まれる場合があります。
try
コードが成功した場合に常に実行する必要がある場合は、try ブロックの最後に配置します。try
ブロック内の前のコードが例外なく実行される限り、実行されます。
try
{
// normal code
// code to run if try stuff succeeds
}
catch (...)
{
// handler code
}
finally
{
// finally code
}
「成功した」コードに対して別の例外処理が必要な場合は、いつでも try/catch をネストできます。
try
{
// normal code
try
{
// code to run if try stuff succeeds
}
catch (...)
{
// catch for the "succeded" code.
}
}
catch (...)
{
// handler code
// exceptions from inner handler don't trigger this
}
finally
{
// finally code
}
「成功した」コードを最終的に実行する必要がある場合は、変数を使用します。
bool caught = false;
try
{
// ...
}
catch (...)
{
caught = true;
}
finally
{
// ...
}
if(!caught)
{
// code to run if not caught
}
例外をスローする可能性のあるコードの後に配置するだけです。
例外がスローされた場合は実行されず、スローされなかった場合は実行されます。
try
{
// Code to check
// Code that I want to run if it's all OK ?? <-- here
}
catch(Exception ex)
{
// Code here if an error
}
finally
{
// Code that runs always
}
try {
// Code that might fail
// Code that gets execute if nothing failed
}
catch {
// Code getting execute on failure
}
finally {
// Always executed
}
私は次のように書きます: メソッドへの呼び出しが正常に実行された場合、その成功は単にtry
try
{
DoSomethingImportant();
Logger.Log("Success happened!");
}
catch (Exception ex)
{
Logger.LogBadTimes("DoSomethingImportant() failed", ex);
}
finally
{
Logger.Log("this always happens");
}