【问题标题】:Exception handling, Is this example good practice?异常处理,这个例子是好习惯吗?
【发布时间】:2015-12-28 01:50:31
【问题描述】:

我主要在异常处理中使用 Try Catch.. 并使用 Exit Sub 来终止方法

在此代码示例中:

应该做些什么来防止冗余代码(即提交和关闭连接)

'connect to DB

  Try

    'insert / update statement

  Catch ex as Exception

   'rollback
   'commit
   'closeDBConnection
      Exit Sub

  End Try

'commit
'close DBconnection

使用 Exit Sub 是个好习惯吗?

【问题讨论】:

  • 你不能用 finally 来做这个吗?
  • 我的问题是不会退出子忽略 finally 块?
  • 没有。 Exit sub/return 不要打断try-finally。 Finally 仍将完成
  • @T.S.谢谢你的解释。这就是我要找的。您能否将此作为答案并提供参考(如果有)。所以我可以接受

标签: vb.net exception-handling


【解决方案1】:

Exit sub/return,或在 try 内发生的异常 - 不要绕过finally 块。最终还是会完成。

完整解释请参见https://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx

【讨论】:

    【解决方案2】:

    将提交语句放在 Try 块的末尾。也可以使用 finally 块进行一些清理。

    Try
        ' insert / update statement
        ' commit
    Catch ex As Exception
        ' rollback
    Finally
        ' close DB connection
    End Try
    

    【讨论】:

    • 加号建议使用 finally Block 并快速回答
    猜你喜欢
    • 1970-01-01
    • 2010-09-11
    • 2021-07-17
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多