尝试catch finally块..在处理global.asax中的错误时,我仍然需要它们吗?

时间:2010-06-02 11:13:30

标签: vb.net exception exception-handling try-catch

我在这个方法中通过我的global.asax处理错误:

Dim CurrentException As Exception
CurrentException = Server.GetLastError()
Dim LogFilePath As String = Server.MapPath("~/Error/" & DateTime.Now.ToString("dd-MM-yy.HH.mm") & ".txt")
Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter(LogFilePath)
sw.WriteLine(DateTime.Now.ToString)
sw.WriteLine(CurrentException.ToString())
sw.Close()

在我的代码中,我目前没有其他错误处理。我还应该插入try,catch,finally块吗?

感谢。

1 个答案:

答案 0 :(得分:2)

绝对

您应始终尽可能靠近源处理异常。这使您可以进行适当的响应,例如重试失败的操作,关闭所有打开的资源,向用户提供反馈,或者编写比堆栈跟踪更具体的日志信息(上下文等)。

然后,您可以(如果您愿意)再次为您的全局“catch all”错误处理抛出异常,但除非是一个微不足道或意外的情况,您应该检查源上的潜在异常。当您编写的代码可能非常合理地抛出异常(通常是文件IO等)但不一定表示致命错误时,尤其如此。