「使用する」のポイントは、オブジェクトのDisposeメソッドが呼び出されることを保証することであると理解しています。しかし、「using」ステートメント内の例外はどのように処理する必要がありますか?例外がある場合は、「using」ステートメントをtrycatchでラップする必要があります。例えば:
usingパラメータ内のオブジェクトの作成で作成された例外があるとしましょう
try
{
// Exception in using parameter
using (SqlConnection connection = new SqlConnection("LippertTheLeopard"))
{
connection.Open();
}
}
catch (Exception ex)
{
}
またはusingスコープ内の例外
using (SqlConnection connection = new SqlConnection())
{
try
{
connection.Open();
}
catch (Exception ex)
{
}
}
すでにtrycatchで例外を処理する必要がある場合は、オブジェクトの破棄も処理する必要があるようです。この場合、「using」ステートメントはまったく役に立たないようです。「using」ステートメントで例外を適切に処理するにはどうすればよいですか?私が見逃しているこれへのより良いアプローチはありますか?
SqlConnection connection2 = null;
try
{
connection2 = new SqlConnection("z");
connection2.Open();
}
catch (Exception ex)
{
}
finally
{
IDisposable disp = connection2 as IDisposable;
if (disp != null)
{
disp.Dispose();
}
}
「using」キーワードの構文はもう少し甘くなります
か...これがあるといいでしょう:
using (SqlConnection connection = new SqlConnection())
{
connection.Open();
}
catch(Exception ex)
{
// What went wrong? Well at least connection is Disposed
}