下記のコードで
警告 変数 'sqlTrans' は、値が割り当てられる前に使用されています。
Null 参照の例外が実行時に発生する可能性があります。
無視をしても問題なさそうですが、これを回避する方法は有りますでしょうか。
よろしくお願いいたします。
Private Sub test()
Dim conn As New SqlConnection
Dim sqlTrans As SqlTransaction
Try
conn.Open()
sqlTrans = conn.BeginTransaction(IsolationLevel.Serializable)
Catch ex As Exception
Finally
If Not sqlTrans.Connection Is Nothing Then
sqlTrans.Rollback()
End If
End Try
End Sub
そのコードだと、もし、Openメソッドで例外が発生した場合、
sqlTrans は Nothing のままになっているわけですから、
Finally ブロックで Null 参照の例外が発生しますよね。
sqlTrans.Connection が空かどうかを確認する前に、
sqlTrans 自体が空かどうかをチェックするようにしてみてください。
魔界の仮面弁士さん、有難うございます。
If Not sqlTrans Is Nothing Then
If Not sqlTrans.Connection Is Nothing Then
sqlTrans.Rollback()
End If
End If
としても、
If Not sqlTrans Is Nothing Then
のところで同じ結果になります。
もしかしたら、宣言の時に
Dim sqlTrans As SqlClient.SqlTransaction = Nothing
としなければいけないのでしょうか。
よろしくお願いします。
| ツイート |
|