我有一个与电子邮件交互的程序。我正在将其从
vb6
升级为 vb.net
。之前在程序中使用 On Error
命令进行了大量的错误处理,以确保它永远不会崩溃,只是忽略并记录错误。在大多数函数中都有这样的 On Error
代码,它通过返回默认值并退出函数来处理函数中的错误。例如:
Public Function Init() As Boolean
On Error GoTo Err_Init
Init = True
Exit_Init:
Exit Function
Err_Init:
Init = False
Resume Exit_Init
End Function
我想将所有错误处理更改为
Try - Catch
块。当我升级 vb6
代码时,我最初的想法是用 Try - Catch
入口点周围的简单 Sub Main
替换所有错误处理,如下所示:
Public Sub Main()
Try
Init()
catch
'do stuff
end try
End Sub
public function Init() As boolean
init = true
end function
因为程序中的任何错误都会以这种方式被捕获,我可以一次性处理它们
Try - Catch
。
但是我后来意识到,当发生错误时,这不会使上面的函数返回值
False
。如果我仍然想要此功能,我是否必须将所有内容包装在 Try
块中?
由于您担心的是您不希望应用程序崩溃或损坏,所以您可以使用 Try 缓存块来解决该问题。 但是,如果您正在谈论整个应用程序中的错误处理,那么我建议您考虑一种重构整个代码的方法。 删除所有“On Error”语句并应用一些新逻辑来处理错误。 该逻辑可能会有所不同(仅日志记录、重试策略设计模式等)考虑所有预期错误并相应地处理它们。
如果您需要对特定函数中的错误执行一些特殊操作,那么该函数应该有自己的 Try/Catch 块来实现该行为。例如:
Public Function Init() As Boolean
Try
'Presumably some other code goes here
Return True
Catch ex As Exception
Return False
End Try
End Function
摆脱所有错误步骤并进行全局错误处理
在main_load中放置下面的三个块
' Get your application's application domain for error handling.
Dim currentDomain As AppDomain = AppDomain.CurrentDomain
' Define a handler for unhandled exceptions.
AddHandler currentDomain.UnhandledException, AddressOf MYExnHandler
' Define a handler for unhandled exceptions for threads behind forms.
AddHandler Application.ThreadException, AddressOf MYThreadHandler
然后添加如下所示的两个子例程
Private Sub MYExnHandler(ByVal sender As Object,
ByVal e As UnhandledExceptionEventArgs)
Dim EX As Exception
EX = e.ExceptionObject
If EX.StackTrace.Contains("SOMETHING") Then
My.Computer.FileSystem.WriteAllText(LogToWrite, "Error SOMETHING caught:" & EX.StackTrace & vbCrLf, True, System.Text.Encoding.Default)
MsgBox("error caught. Contact **XXX** for assistance!" & vbCrLf & vbCrLf & "Error: " & vbCrLf & EX.StackTrace,, "Fatal Error")
End If
End Sub
Private Sub MYThreadHandler(ByVal sender As Object,
ByVal e As Threading.ThreadExceptionEventArgs)
If e.Exception.StackTrace.Contains("SOMETHING") Then
My.Computer.FileSystem.WriteAllText(LogToWrite, "Error SOETHING caught:" & e.Exception.StackTrace & vbCrLf, True, System.Text.Encoding.Default)
MsgBox("Error caught. Contact **xxx** for assistance!" & vbCrLf & vbCrLf & "Error: " & vbCrLf & e.Exception.StackTrace,, "Fatal Error")
End If
End Sub
您可以检查错误的内容,并使用案例数组对每个错误做出相应的响应..
多年来,我发现 Try 语句在一半的情况下是有效的。有时,您可以使用此方法,有时它会绕过不执行的代码。在编码时了解错误处理代码很重要,最好有我为您提供的错误处理代码列表和示例用法:
0
3 Return without GoSub
5 Invalid procedure call or argument
6 Overflow
7 Out of memory
9 Subscript out of range
10 This array is fixed or temporarily locked
11 Division by zero
13 Type mismatch
14 Out of string space
16 Expression too complex
17 Can't perform requested operation
18 User interrupt occurred
20 Resume without error
28 Out of stack space
35 Sub or Function not defined
47 Too many DLL application clients
48 Error in loading DLL
49 Bad DLL calling convention
51 Internal error
52 Bad file name or number
53 File not found
54 Bad file mode
55 File already open
57 Device I/O error
58 File already exists
59 Bad record length
61 Disk full
62 Input past end of file
63 Bad record number
67 Too many files
68 Device unavailable
70 Permission denied
71 Disk not ready
74 Can't rename with different drive
75 Path/File access error
76 Path not found
91 Object variable or With block variable not set
92 For loop not initialized
93 Invalid pattern string
94 Invalid use of Null
96 Unable to sink events of object because the object is already firing events to the maximum number of event receivers that it supports
97 Can not call friend function on object which is not an instance of defining class
98 A property or method call cannot include a reference to a private object, either as an argument or as a return value
321 Invalid file format
322 Can't create necessary temporary file
325 Invalid format in resource file
380 Invalid property value
381 Invalid property array index
382 Set not supported at runtime
383 Set not supported (read-only property)
385 Need property array index
387 Set not permitted
393 Get not supported at runtime
394 Get not supported (write-only property)
422 Property not found
423 Property or method not found
424 Object required
429 ActiveX component can't create object
430 Class does not support Automation or does not support expected interface
432 File name or class name not found during Automation operation
438 Object doesn't support this property or method
440 Automation error
442 Connection to type library or object library for remote process has been lost. Press OK for dialog to remove reference.
443 Automation object does not have a default value
445 Object doesn't support this action
446 Object doesn't support named arguments
447 Object doesn't support current locale setting
448 Named argument not found
449 Argument not optional
450 Wrong number of arguments or invalid property assignment
451 Property let procedure not defined and property get procedure did not return an object
452 Invalid ordinal
453 Specified DLL function not found
454 Code resource not found
455 Code resource lock error
457 This key is already associated with an element of this collection
458 Variable uses an Automation type not supported in Visual Basic
459 Object or class does not support the set of events
460 Invalid clipboard format
461 Method or data member not found
462 The remote server machine does not exist or is unavailable
463 Class not registered on local machine
481 Invalid picture
482 Printer error
735 Can't save file to TEMP
744 Search text not found
746 Replacements too long
USAGE EXAMPLE:
Option Explicit
Private Sub Form_Load()
Dim i As Integer
For i = 0 To 32000
If Error$(i) <> "Application-defined or object-defined error" Then
Debug.Print i, Error$(i)
End If
Next i
End Sub