FreeBasic On Error Keyword
last modified June 16, 2025
The FreeBasic On Error keyword enables structured error handling
in programs. It allows developers to gracefully handle runtime errors rather
than having the program crash unexpectedly.
Basic Definition
In FreeBasic, On Error establishes an error handling routine.
When an error occurs, execution jumps to the specified error handler. This
provides control over how the program responds to unexpected conditions.
The On Error statement has several forms: On Error Goto,
On Error Resume Next, and On Error Goto 0. Each serves
different purposes in error management.
Simple Error Handling with On Error Goto
This example demonstrates basic error handling using On Error Goto.
We use a file operation that attempts to open a non-existent fileāthis reliably
triggers an error.
Sub Main()
On Error Goto ErrorHandler
Dim x As Integer = 10
Dim y As Integer = 0
Dim result As Integer = x \ y ' Integer division by zero
Print "Result: "; result
Exit Sub
ErrorHandler:
Print "Error occurred: "; Err
Resume Next
End Sub
Main()
In this example, we attempt integer division by zero, which triggers the
error handler. The error handler prints the error number and uses
Resume Next to continue execution. Note that FreeBasic's
On Error primarily catches runtime errors like division by zero,
array bounds violations, and similar mathematical or memory errors.
Resuming Execution with On Error Resume Next
On Error Resume Next continues execution after an error occurs.
Sub Main()
On Error Resume Next
Dim values(5) As Integer = {10, 20, 0, 5, 0, 15}
Dim result As Integer
For i As Integer = 0 To 5
result = 100 \ values(i) ' Integer division
If Err Then
Print "Division by zero at index "; i
Err = 0 ' Clear the error
Else
Print "100 / "; values(i); " = "; result
End If
Next
End Sub
Main()
This code attempts to divide 100 by each array element. When it encounters zero,
it continues to the next iteration instead of stopping. The Err
check determines if an error occurred, and Err = 0 clears it.
This demonstrates how On Error Resume Next allows the program to
handle errors gracefully without terminating.
Nested Error Handlers
Error handlers can be nested to handle different types of errors separately.
Sub ProcessArray()
On Error Goto ArrayError
Dim arr(5) As Integer = {1, 2, 0, 4, 5}
For i As Integer = 0 To 5
On Error Goto DivisionError
Dim result As Integer = 100 \ arr(i)
Print "100 / "; arr(i); " = "; result
Next
Exit Sub
ArrayError:
Print "Array access error: "; Err
Exit Sub
DivisionError:
Print "Division error at index "; i; ": "; Err
Resume Next
End Sub
ProcessArray()
This example shows nested error handling. The outer handler catches array access errors, while the inner handler catches division by zero errors. Each error type gets specific handling while maintaining program flow.
Disabling Error Handling with On Error Goto 0
On Error Goto 0 turns off error handling in the current scope.
Sub Main()
On Error Goto Handler
Print "Before error handling disabled"
On Error Goto 0
Dim x As Integer = 10 \ 0 ' This will crash the program
Print "This line won't execute"
Exit Sub
Handler:
Print "Error caught: "; Err
Resume Next
End Sub
Main()
After On Error Goto 0, any errors will cause the program to
terminate rather than being caught by the handler. This is useful when you
want to ensure certain sections of code run without error protection.
Error Handling in Functions
Functions can use error handling to validate parameters or operations.
Function SafeDivide(numerator As Integer, denominator As Integer) As Double
On Error Goto DivError
Return numerator / denominator
Exit Function
DivError:
Print "Division error - returning 0"
Return 0
End Function
Print "10 / 2 = "; SafeDivide(10, 2)
Print "10 / 0 = "; SafeDivide(10, 0)
This function safely handles division by returning 0 when division fails. The error handler prevents crashes while providing a sensible default value. The calling code doesn't need to implement its own error checking.
Using Err Function
FreeBasic provides the Err variable to get error numbers.
Sub Main()
On Error Goto ErrorHandler
' Trigger different errors
Dim x As Integer = 10 \ 0 ' Division by zero
'Dim arr(5) As Integer : arr(10) = 1 ' Array bounds
Exit Sub
ErrorHandler:
Print "Error number: "; Err
Select Case Err
Case 11:
Print "Division by zero error"
Case 9:
Print "Array subscript out of range"
Case Else:
Print "Unknown error"
End Select
Resume Next
End Sub
Main()
This code demonstrates accessing error information. Err contains
the error number. Different error numbers correspond to different types of
runtime errors. You can use Select Case to handle specific error types
differently.
Advanced Error Handling with Resume
The Resume statement allows sophisticated error recovery.
Sub ProcessData()
On Error Goto DataError
Dim attempts As Integer = 0
RetryPoint:
attempts += 1
' Simulate unreliable operation
If attempts < 3 And Int(Rnd() * 10) < 7 Then
Print "Operation failed (attempt "; attempts; ")"
Dim x As Integer = 10 \ 0 ' Trigger error
End If
Print "Operation succeeded after "; attempts; " attempts"
Exit Sub
DataError:
Print "Error occurred (attempt "; attempts; ")"
If attempts < 3 Then
Sleep 1000 ' Wait before retry
Resume RetryPoint
Else
Print "Giving up after 3 attempts"
End If
End Sub
Randomize Timer
ProcessData()
This example implements retry logic using Resume. The operation
has a 70% chance of failing for the first two attempts. The error handler
retries up to three times before giving up. Resume continues
execution at the specified label.
Best Practices
- Specific Handlers: Create separate handlers for different error types.
- Resource Cleanup: Always release resources in error handlers.
- Error Information: Log detailed error info for debugging.
- Limited Scope: Use
On Error Goto 0when protection isn't needed. - Recovery: Only use
Resumewhen errors can be corrected.
This tutorial covered FreeBasic's On Error keyword with practical
examples showing various error handling techniques. Proper error handling makes
programs more robust and user-friendly.
Author
List all FreeBasic Tutorials.