Choosing the Right On Error Strategy in Visual Basic: A Practical Guide
A practical guide to selecting and implementing the right On Error variant (GoTo, Resume Next, GoTo 0) in VB6, VBA, and VB.NET, with concrete patterns, verification steps, and recovery options.
06 Feb 2026, 23:44 UTC

Understanding the Error Handling Landscape
Visual Basic's On Error statement remains the primary mechanism for runtime error handling across VB6, VBA, and VB.NET. While VB.NET introduces structured exception handling with Try/Catch/Finally, the legacy On Error syntax persists for compatibility and specific scenarios where procedural control flow is preferred. The challenge isn't learning the syntax—it's selecting the variant that matches your reliability requirements without introducing silent failures.
Desired Outcome
Implement error handling that surfaces genuine problems during development, recovers gracefully from expected runtime conditions in production, and never masks bugs behind silent continuation.
Prerequisites
- A Visual Basic environment: VB6 IDE, VBA host (Excel, Access, etc.), or VB.NET project targeting .NET Framework or .NET Core
- Familiarity with the
Err object'sNumber,Description, andSource properties - Ability to run test procedures and inspect the Immediate Window or debug output
Strategy Selection Matrix
| Scenario | Recommended Variant | Rationale |
|---|---|---|
| General procedure with recoverable error paths | On Error GoTo <label> | Centralizes cleanup, preserves call stack, enables Resume/ |
| Single statement that may fail predictably (e.g., file existence check) | On Error Resume Next (scoped) | Defers handling to immediate next line; must reset immediately |
| Library code that must not swallow caller's error context | On Error GoTo 0 | Disables local handling, propagates error naturally |
| Migration from VB6 to VB.NET | Prefer Try/Catch | Structured handling integrates with .NET exception hierarchy |
Focused Procedure: Implementing Labeled Error Handling
The On Error GoTo <label> pattern provides the most control. Follow this structure:
- Declare the handler label at the procedure's end, after the normal exit point.
- Enable handling with
On Error GoTo ErrorHandler at the procedure start. - Inspect
Errto decide: retry, log, clean up, or re-raise. - Exit cleanly via
Exit Sub/Exit Function before the handler. - Reset state with
On Error GoTo 0 if re-enabling strict mode locally.
Public Function ReadConfigValue(ByVal key As String) As String
On Error GoTo ErrorHandler
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
' Normal logic
Dim ts As Object
Set ts = fso.OpenTextFile("config.ini", 1) ' ForReading = 1
ReadConfigValue = ts.ReadAll
ts.Close
Exit Function
ErrorHandler:
Select Case Err.Number
Case 53 ' File not found
ReadConfigValue = "DEFAULT"
Resume Next
Case 70 ' Permission denied
Err.Raise vbObjectError + 513, "ReadConfigValue", _
"Cannot access config.ini: " & Err.Description
Case Else
' Log unexpected errors, then re-raise
Debug.Print "Unexpected error " & Err.Number & ": " & Err.Description
Err.Raise Err.Number, Err.Source, Err.Description
End Select
End Function
Where to run: Paste into a standard module in VB6, VBA, or VB.NET (with Option Strict Off). Requires reference to "Microsoft Scripting Runtime" for early binding, or late binding as shown.
Scoped Resume Next: The Safe Pattern
On Error Resume Next is useful for single statements where failure is expected and benign—checking if a key exists in a collection, attempting to delete a temporary file, or querying an optional registry value. The critical rule: reset it on the very next line.
Public Function KeyExists(ByVal dict As Object, ByVal key As String) As Boolean
On Error Resume Next
Dim dummy As Variant
dummy = dict(key) ' Raises error 5 if key missing
KeyExists = (Err.Number = 0)
On Error GoTo 0 ' Reset immediately
End Function
Without the immediate On Error GoTo 0, subsequent lines execute with error handling disabled, turning any bug into a silent wrong result.
Mixing Variants: What Goes Wrong
The research flags a specific hazard: mixing On Error GoTo and On Error Resume Next in the same procedure creates ambiguous Err state. Consider this sequence:
Sub DemonstrateHazard()
On Error GoTo Handler
Err.Raise 1001, "Test", "First error"
Handler:
On Error Resume Next ' Masks the original error context
Err.Raise 1002, "Test", "Second error"
' Err.Number now shows 1002, original 1001 is lost
On Error GoTo 0
Exit Sub
End Sub
After the Resume Next, the Err object reflects only the most recent error. If your handler logic depends on the original error number, you've lost it. Rule: pick one variant per procedure. If you need scoped Resume Next, isolate it in a helper function.
Verification Steps
Confirm behavior in your target environment before committing to a pattern:
- Create a test module with procedures exercising each variant.
- Trigger deliberate errors: division by zero (
x = 1/0), file not found, type mismatch. - Inspect
Errin the Immediate Window after each statement:? Err.Number, Err.Description, Err.Source - Verify
On Error GoTo 0restores unhandled error propagation—run the test without a handler and confirm the IDE breaks or the host displays the error dialog.
Run these tests in each target dialect (VB6, VBA host, VB.NET) because VB.NET's On Error maps to System.Exception internally, and the Err object is a compatibility wrapper with slightly different timing.
Limitations and Dialect Differences
- VB.NET:
On Error is supported but discouraged. StructuredTry/Catch catches CLR exceptions (includingStackOverflowException whichOn Error cannot). TheErr object only reflects the last unmanaged error. - VBA hosts: Some hosts (e.g., older Access versions) reset
Err between event procedures. StoreErr.Number/Description in module-level variables if you need persistence. - VB6: No
Finally equivalent. Cleanup code must appear in both the normal exit path and the error handler, or use a shared label with a flag variable.
Practical Check: Did It Work?
After implementing error handling in a production procedure:
- Force each anticipated error condition (disconnect network, lock file, invalid input).
- Verify the application logs the expected message, shows the user-friendly dialog, or returns the documented fallback value.
- Confirm no "silent success" cases: add a temporary
Debug.Print "Handler reached: " & Err.Number in the handler, run the full test suite, and search the output for unexpected entries.
Recovery Options
If a deployed error handler behaves incorrectly:
- Immediate mitigation: Add a wrapper function with
On Error GoTo 0 around the problematic call to force propagation. - Patch: Replace the procedure's error handling with a corrected version; recompile and redeploy the module (VBA) or assembly (VB.NET).
- Rollback: If the change was part of a larger release, revert the specific module to the previous version. No database or state migration is involved—
On Error changes are purely behavioral.
Decision Summary
Default to On Error GoTo <label> for procedures with multiple failure points. Reserve On Error Resume Next for single-line checks with immediate reset. Use On Error GoTo 0 to deliberately propagate errors from library code. In VB.NET, migrate to Try/Catch for new code—but understand On Error well enough to maintain the legacy modules you'll inevitably encounter.