特定の条件が満たされたときにキャッチハンドラーを実行できるC#のこの新機能を見つけました。
int i = 0;
try
{
throw new ArgumentNullException(nameof(i));
}
catch (ArgumentNullException e)
when (i == 1)
{
Console.WriteLine("Caught Argument Null Exception");
}
これがいつ役立つかを理解しようとしています。
次のようなシナリオが考えられます。
try
{
DatabaseUpdate()
}
catch (SQLException e)
when (driver == "MySQL")
{
//MySQL specific error handling and wrapping up the exception
}
catch (SQLException e)
when (driver == "Oracle")
{
//Oracle specific error handling and wrapping up of exception
}
..
しかし、これも同じハンドラ内で実行でき、ドライバの種類に応じて異なるメソッドに委任できるものです。これにより、コードが理解しやすくなりますか?間違いなく違います。
私が考えることができる別のシナリオは次のようなものです:
try
{
SomeOperation();
}
catch(SomeException e)
when (Condition == true)
{
//some specific error handling that this layer can handle
}
catch (Exception e) //catchall
{
throw;
}
繰り返しますが、これは私ができることです:
try
{
SomeOperation();
}
catch(SomeException e)
{
if (condition == true)
{
//some specific error handling that this layer can handle
}
else
throw;
}
'catch、when'機能を使用すると、ハンドラー自体がスキップされ、スタックの巻き戻しがハンドラー内の特定のユースケースの処理に比べてはるかに早く発生するため、例外処理が速くなりますか?この機能により適した特定の使用例はありますか?
try..catch...catch..catch..finally
ますか?
catch (Exception ex)
、型のチェックなどしかできませんthrow
。少し整理されたコード(コードノイズの回避)が、この機能が存在する理由です。(これは実際には多くの機能に当てはまります。)
when
例外自体にアクセスする必要がある場合に役立ちます