PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197
The best error handling for VB6-VBForums
Results 1 to 18 of 18

Thread: The best error handling for VB6

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Apr 2009
    Posts
    113

    The best error handling for VB6

    Can anyone provide me with a link to the best error handling tutorial out there?

  2. #2
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    32,400

    Re: The best error handling for VB6

    fortunately in VB6, there isn't much to it...

    basically it looks like this:
    Code:
    On Error GoTo myErrHandler
    
    'Put the body of the sub/function/what ever here....
    
    :exitClean
    
    Exit Sub 'Or Function, what ever
    
    :myErrHandler
    'Do what you need to do to handle the error here
    Resum cleanExit
    End Sub 'function, what ever
    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Apr 2009
    Posts
    113

    Re: The best error handling for VB6

    I understand the basics but am looking to create my own error handler so am after something more advanced, thought someone might know where i can find this information to save me reading 100's of tutorials

  4. #4
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,085

    Re: The best error handling for VB6

    For some more information, see the article Why do errors crash my program, and how can I stop that from happening? (making an Error Handler) from our Classic VB FAQs (in the FAQ forum)

    You can take things further by making a Sub/Function to do the actual handling, and detect exactly which line of code the error occurred on, etc. There is an explanation of the method I use here.

  5. #5
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Candon City, Ilocos Sur, Phils.
    Posts
    11,007

    Re: The best error handling for VB6

    I have also something in my sig which is for error handling.
    Regards,


    As a gesture of gratitude please consider rating helpful posts. c",)

    Some stuffs: Mouse Hotkey | Compress file using SQL Server! | WPF - Rounded Combobox | WPF - Notify Icon and Balloon | NetVerser - a WPF chatting system

  6. #6
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,612

    Re: The best error handling for VB6

    Install MZTools. It is a great time saver for such tasks. It can automatically inserts the error handler code for you.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." Charles F. Kettering

    Read articles on My Blog 101 LINQ Samples JSON Validator XML Schema Validator "How Do I" videos on MSDN VB.NET and C# Comparison Good Coding Practices VBForums Reputation Saver String Enum Super Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  7. #7

    Thread Starter
    Lively Member
    Join Date
    Apr 2009
    Posts
    113

    Re: The best error handling for VB6

    Pradeep1210, In-stalled MZ Tools it's perfect for numbering lines of code as well!

    @ Dee-u looking into stack tracing, thanks for that!

  8. #8
    PowerPoster isnoend07's Avatar
    Join Date
    Feb 2007
    Posts
    3,237

    Re: The best error handling for VB6

    You could put this in a module and it will display the error and write to a log file: Uses line numbers with MZTools
    Code:
    Public Sub ShowError(ErrNumber As Long, ErrDesc As String, strTitle As String, iLineNu As Integer)
        On Error GoTo ShowError
        Dim fh As Integer
        Dim sfilename As String
        fh = FreeFile
        sfilename = gMyPath & "\error.log"
        FileExists sfilename
        Open sfilename For Append As fh
        Print #fh, Format(Now, "dd-mm-yyyy hh:nn:ss") _
       & ErrNumber & " " & ErrDesc & " - " & strTitle & " Line Number: " & iLineNu
        Close fh
        
        Screen.MousePointer = vbDefault
        MsgBox "Error: " & ErrNumber & vbNewLine & ErrDesc, vbOKOnly + vbExclamation  ', strTitle
        
        Exit Sub
        
    ShowError:
        Screen.MousePointer = vbDefault
        
        MsgBox "Error: " & err.Number & vbNewLine & err.Description, vbOKOnly + vbExclamation   ', "Show Error"
       
        Exit Sub
    End Sub
    Waiting for a full featured smart phone with out marrying a provider
    Go Android
    Go raiders

  9. #9

    Thread Starter
    Lively Member
    Join Date
    Apr 2009
    Posts
    113

    Re: The best error handling for VB6

    isnoend07 thanks for the advice but take a look at the error handling in dee-u's sig it includes what you have suggested and a lot more. I think I'll be studying his code for hours to help me understand it to be able to make my own.

  10. #10
    PowerPoster isnoend07's Avatar
    Join Date
    Feb 2007
    Posts
    3,237

    Re: The best error handling for VB6

    Quote Originally Posted by vb help View Post
    isnoend07 thanks for the advice but take a look at the error handling in dee-u's sig it includes what you have suggested and a lot more. I think I'll be studying his code for hours to help me understand it to be able to make my own.
    You should use dee-u's, very through. Couple things you may want written to the log if not already included for distributed apps:
    OS
    Version of your software minor & major
    path to your exe
    path to your data files
    Running as Admin ?
    I also have a custom ocx that silently emails me any errors thru an online jmail if my app has any problems a sample:
    Code:
    ==Software Details==
    Program Name  : MyApp(10.8.77)
    App ExeName   : MyExe
    App Path      : C:\Program Files\MyApp
    
    ==Computer Details==
    OS Name       : Windows Vista - Service Pack 1
    Processor Info: x86 Family 6 Model 15 Stepping 13, GenuineIntel - Cores : 2
    Computer/User : computerName / Owner
    Computer Date : 8/13/2009 7:09:11 AM
    Server Date   : 13/08/2009 15:09:12
    
    ==Error Details==
    Module Name   : Backupper
    Function Name : Function BackupSize(Optional Folder As String)
    Line Number   : 170
    Error Number  : 6
    Error Desc    : Overflow
    
    Custom Message: Error
    
    ==Connection Details==
    Local IP      : 192.168.2.13
    Remote IP     : 92.48.75.11
    
    The user is behind a router/firewall
    With the above info i was able to pinpoint the problem, easily.
    had a long variable type and fixed by using a double within minutes
    Waiting for a full featured smart phone with out marrying a provider
    Go Android
    Go raiders

  11. #11

    Thread Starter
    Lively Member
    Join Date
    Apr 2009
    Posts
    113

    Re: The best error handling for VB6

    thanks isnoend07 that's an interesting read, i'll take ideas away from it and let you know how i get on

  12. #12
    Hyperactive Member
    Join Date
    Aug 2006
    Location
    TeXaS
    Posts
    497

    Re: The best error handling for VB6

    in my opinion you should use error handling when only absolute necessary. most every thing you do that can possibly error can be avoided or checked beforehand when writing code. there are rare occasions where what you do cannot be done without some type of error handling, but those are pretty rare. i can see using it on file i/o operations as well. you never know if a drive has some kind of fault until its too late. what my point is, is that you should learn to code correctly to avoid errors, think about what the user could do to screw up your application and put in checks to avoid these issues. don't use the error handling as a crutch to handle events that you could have avoided with a bit of extra code.

  13. #13
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,612

    Re: The best error handling for VB6

    Quote Originally Posted by isnoend07 View Post
    I also have a custom ocx that silently emails me any errors thru an online jmail if my app has any problems
    That's a bad practice and should never be done. It might also be illegal in some countries. Always ask for user's confirmation before sending any unexpected email from your application.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." Charles F. Kettering

    Read articles on My Blog 101 LINQ Samples JSON Validator XML Schema Validator "How Do I" videos on MSDN VB.NET and C# Comparison Good Coding Practices VBForums Reputation Saver String Enum Super Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  14. #14
    PowerPoster isnoend07's Avatar
    Join Date
    Feb 2007
    Posts
    3,237

    Re: The best error handling for VB6

    Quote Originally Posted by Pradeep1210 View Post
    That's a bad practice and should never be done. It might also be illegal in some countries. Always ask for user's confirmation before sending any unexpected email from your application.
    You are right
    my app prompts with the info being sent and a checkbox to not ask again and it's in the license agreement. I might be taking it out pretty soon as my apps never get any errors anymore.
    Waiting for a full featured smart phone with out marrying a provider
    Go Android
    Go raiders

  15. #15
    Hyperactive Member
    Join Date
    Jul 2006
    Posts
    398

    Re: The best error handling for VB6

    do you have version for .net?
    ________
    VOLCANO CLASSIC
    Last edited by rothj0hn; Feb 15th, 2011 at 02:05 PM.

  16. #16
    PowerPoster TysonLPrice's Avatar
    Join Date
    Sep 2002
    Location
    Columbus, Ohio
    Posts
    3,298

    Re: The best error handling for VB6

    Quote Originally Posted by Billy Conner View Post
    in my opinion you should use error handling when only absolute necessary. most every thing you do that can possibly error can be avoided or checked beforehand when writing code. there are rare occasions where what you do cannot be done without some type of error handling, but those are pretty rare. i can see using it on file i/o operations as well. you never know if a drive has some kind of fault until its too late. what my point is, is that you should learn to code correctly to avoid errors, think about what the user could do to screw up your application and put in checks to avoid these issues. don't use the error handling as a crutch to handle events that you could have avoided with a bit of extra code.


    I have to disagree with that. Yes you should code for every possible error you can think of but I'd challenge anyone to name them all. Maybe in your own personal apps you can get away with that but in a production environment an app may be around for years with many different people with varying levels of skill maintaining it. If I came into a shop and had to debug an error that someone didn't trap I'd be POed. For example a DBA changes a table's column name not thinking about an app using it. Would you code for that in advance by checking if a column exist before referencing it? There are a myriad of things that can happen un-expectantly in a production environment. Better safe, spend a few minutes putting error handling everywhere up front, then sorry.

  17. #17
    PowerPoster Ellis Dee's Avatar
    Join Date
    Mar 2007
    Location
    New England
    Posts
    3,527

    Re: The best error handling for VB6

    Here's mine, which also supports stack tracing. I attached a simple test project (bas only; just double-click to open it and then Run it) as proof of concept.
    vb Code:
    1. Public Const ErrorIgnore = vbObjectError + 513
    2. Public Const ErrorNotice = vbObjectError + 514
    3. Public Const ErrorData = vbObjectError + 515
    4. Public Const ErrorFail = vbObjectError + 516
    5.  
    6. Public Enum ErrorHandlerActions
    7.     eaEnter
    8.     eaExit
    9.     eaLog
    10.     eaNotify
    11.     eaRaise
    12.     eaRoot
    13. End Enum
    14.  
    15. ' ErrorHandler()
    16. ' This function is designed to offer robust and flexible
    17. ' error handling with a minimum of impact to the bulk of
    18. ' your code. It allows you to handle errors in data
    19. ' modules, classes, or generic utilities seemlessly.
    20. '
    21. ' Concept
    22. ' Use "On Error" trapping only in root-level functions
    23. ' (defined as any event procedure fired by a user
    24. ' interaction or timer control) and functions that require
    25. ' a close-down section, such as those that access a
    26. ' database or create objects. No other error trapping
    27. ' is required. (The root-level trapping will catch any
    28. ' subsequent errors down the call stack, so additional
    29. ' trapping would be redundant.)
    30. '
    31. ' Requirements
    32. ' ErrorHandler() requires a public enumeration as follows:
    33. 'Public Enum ErrorHandlerActions
    34. '    eaEnter
    35. '    eaExit
    36. '    eaLog
    37. '    eaNotify
    38. '    eaRaise
    39. '    eaRoot
    40. 'End Enum
    41. '
    42. ' Call Stack
    43. ' ErrorHandler() tracks the call stack as provided by you
    44. ' the programmer. Send the function/sub/property/method
    45. ' procedure name to ErrorHandler() as the first line of
    46. ' code in each procedure. You should include the module
    47. ' name as well; one simple idea is to define a private
    48. ' constant in all modules that contains the module name,
    49. ' and then add the function name in each individual call.
    50. '
    51. ' Root-Level functions
    52. ' For root-level functions (which will have error trapping)
    53. ' add to the call stack using the eaRoot action. These are
    54. ' also the functions where user notification is handled by
    55. ' calling the eaNotify action in the error trapping
    56. ' routine. Note that the eaExit action (discussed later)
    57. ' isn't needed in root-level functions. For example:
    58. 'Public Sub List1_Click()
    59. 'On Error GoTo List1_ClickErr
    60. '    ErrorHandler eaRoot, ModuleConstant & ".List1_Click"
    61. '    ' Your code to process the event goes here
    62. '
    63. 'List1_ClickExit:
    64. '    Exit Sub
    65. '
    66. 'List1_ClickErr:
    67. '    ErrorHandler eaNotify
    68. '    Resume List1_ClickExit
    69. 'End Sub
    70. '
    71. ' For "standard" functions, defined as being neither root-
    72. ' level nor requiring a close-down section, manage the
    73. ' call stack by beginning and ending each function with
    74. ' the eaEnter and eaExit actions respectively. Like the
    75. ' eaRoot action, eaEnter requires the function name. Also
    76. ' remember that error trapping is unnecessary in standard
    77. ' functions. Example:
    78. 'Public Sub Refresh()
    79. '    ErrorHandler eaEnter, ModuleConstant & ".Refresh"
    80. '    ' Your code goes here
    81. '    ErrorHandler eaExit
    82. 'End Sub
    83. '
    84. ' In non-root-level functions that require a close-down
    85. ' section, include eaEnter and eaExit actions just like
    86. ' with standard functions, but there is additional support
    87. ' required. Your error trapping that forces a close-down
    88. ' section (releasing objects or closing recordsets) to fire
    89. ' will absorb the actual error, leaving nothing to pass
    90. ' back up the call stack for ErrorHandler() to use in
    91. ' notifying the user. This problem is made worse because
    92. ' errors are typically suppressed (via On Error Resume
    93. ' Next) during close-down sections.
    94. '
    95. ' ErrorHandler() provides a simple solution for this
    96. ' dilemma. Send the eaLog action in the error trapping
    97. ' routine to log the error for later use. In your close-
    98. ' down code, after it is finished be sure error trapping
    99. ' is re-enabled (with On Error Goto 0) and send the
    100. ' eaRaise action to propagate the error back up the call
    101. ' stack. Here is a complete example:
    102. 'Public Function GetEmployeeName() As String
    103. 'On Error GoTo GetEmployeeNameErr
    104. '    ErrorHandler eaEnter, ModuleConstant & ".GetEmployeeName"
    105. '    ' Your code to access data/create objects goes here
    106. '    ErrorHandler eaExit
    107. '
    108. 'GetEmployeeNameExit:
    109. '    On Error Resume Next
    110. '    ' Your code to close recordsets/objects goes here
    111. '    On Error GoTo 0
    112. '    ErrorHandler eaRaise
    113. '    Exit Function
    114. '
    115. 'GetEmployeeNameErr:
    116. '    ErrorHandler eaLog
    117. '    Resume GetEmployeeNameExit
    118. 'End Function
    119. '
    120. ' Custom errors
    121. ' Your program will no doubt either have custom errors, or
    122. ' at least specific custom messages to some default errors.
    123. ' Modify the Select Case statement to handle your specific
    124. ' errors as appropriate.
    125. '
    126. ' Action Summary
    127. ' eaEnter
    128. '     Requires a source name. (Class/Module.Function)
    129. '     Used at start of all non-root-level functions.
    130. ' eaExit
    131. '     No source name required.
    132. '     Used at end of all non-root-level functions.
    133. ' eaLog
    134. '     No source name required.
    135. '     Used in error trapping routine when a close-down
    136. '     section is required. (Function uses data or objects.)
    137. ' eaNotify
    138. '     No source name required.
    139. '     Used in error trapping routine of root-level functions.
    140. ' eaRaise
    141. '     No source name required.
    142. '     Used at end of close-down sections.
    143. ' eaRoot
    144. '     Requires a source name. (Class/Module.Function)
    145. '     Used at start of all root-level functions.
    146. Public Sub ErrorHandler(penAction As ErrorHandlerActions, Optional pstrSource As String)
    147.     Const Delimiter = vbCrLf & "    "
    148.     Static slngNumber As Long
    149.     Static sstrSource As String
    150.     Static sstrDescription As String
    151.     Static sstrCallStack As String
    152.     Dim strMessage As String
    153.     Dim strDetail As String
    154.    
    155.     ' Clear error state if entering a root function
    156.     If penAction = eaRoot Then
    157.         Err.Clear
    158.         slngNumber = 0
    159.         sstrSource = ""
    160.         sstrDescription = ""
    161.         sstrCallStack = ""
    162.     End If
    163.     ' Remove source from list if successfully exiting a function
    164.     If penAction = eaExit Then
    165.         If InStr(sstrCallStack, Delimiter) > 0 Then
    166.             sstrCallStack = Left(sstrCallStack, InStrRev(sstrCallStack, Delimiter, Len(sstrCallStack) - 1) - 1)
    167.         End If
    168.         Exit Sub
    169.     End If
    170.     ' Log source
    171.     If penAction = eaRoot Or penAction = eaEnter Then
    172.         sstrCallStack = sstrCallStack & Delimiter & pstrSource
    173.     End If
    174.     ' Log error number and description if in an error state
    175.     If Err.Number <> 0 Then ' If penAction = eaLog Or penAction = eaNotify Then
    176.         slngNumber = Err.Number
    177.         sstrSource = Err.Source
    178.         sstrDescription = Err.Description
    179.     End If
    180.     ' Raise error
    181.     If penAction = eaRaise And slngNumber <> 0 Then
    182.         Err.Raise slngNumber, sstrSource, sstrDescription
    183.     End If
    184.     ' Notify user
    185.     If penAction = eaNotify And slngNumber <> 0 Then
    186.         ' Update the screen
    187.         Screen.MousePointer = vbNormal
    188.         'UnlockWindow
    189.         strDetail = _
    190.             "Number: " & slngNumber & " (" & slngNumber - vbObjectError & ")" & vbCrLf & _
    191.             "Source: " & sstrSource & vbCrLf & _
    192.             "Description: " & sstrDescription & vbCrLf & vbCrLf & _
    193.             "Call stack:" & sstrCallStack
    194.         ' Show message
    195.         Select Case slngNumber
    196.             Case ErrorIgnore
    197.             Case ErrorNotice
    198.                 MsgBox sstrDescription, vbInformation, "Notice"
    199.             Case Else ' Unexpected error
    200.                 strMessage = sstrDescription & vbCrLf & vbCrLf & "View detail?"
    201.                 If MsgBox(strMessage, vbYesNo + vbInformation + vbDefaultButton2, "Notice") = vbYes Then
    202.                     Clipboard.Clear
    203.                     Clipboard.SetText strMessage, vbCFText
    204.                     strDetail = strDetail & vbCrLf & vbCrLf & "Detail has been copied to the clipboard."
    205.                     MsgBox strDetail, vbExclamation, "Error Detail"
    206.                 End If
    207.         End Select
    208.     End If
    209.     ' Clear error state
    210.     If penAction = eaNotify Then
    211.         Err.Clear
    212.         slngNumber = 0
    213.         sstrCallStack = ""
    214.         sstrDescription = ""
    215.         sstrSource = ""
    216.     End If
    217. End Sub
    Attached Files Attached Files

  18. #18
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,085

    Re: The best error handling for VB6

    Quote Originally Posted by Billy Conner View Post
    in my opinion you should use error handling when only absolute necessary. ...
    I strongly disagree with that particular line, but at at the same time strongly agree with your point of not using error handling as a crutch.

    The way I see it you should do your best to eliminate all errors from your program (including doing pre-emptive checking where apt), but as Tyson said there will be times when something unexpected happens - in which case your program should deal with it gracefully (and preferably store/send info to help you to fix it), rather than crashing.

    In my opinion error handling should be included in every single routine that could potentially have an error - which includes any that do any file handling/database work/setting focus to controls/showing forms/etc.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width