Module 7 - Error Handling

It's time in this module to learn how to intercept any errors which occur in your programs, using something called error-handling.

Choose what you want to learn from the list of lessons above.

This page provides a brief summary of what you've learned in this module.  You can click here to download the example code shown below.

The On Error Statement

You can instruct a procedure to ignore run-time errors using the On Error Resume Next statement.

Sub Ignore_Errors()

 

'ignore errors after the next line

On Error Resume Next

 

'further instructions

 

End Sub

You can disable an error handler using the On Error GoTo 0 statement.

Sub Disable_Error_Handler()

 

'ignore errors after the next line

On Error Resume Next

 

'further instructions

 

'disable previous error handler

On Error GoTo 0

 

'further instructions

 

End Sub

Custom Error Handlers

You can redirect code in the event of an error using the On Error GoTo LineLabel statement.

Sub Custom_Error_Handler()

 

On Error GoTo ErrorSection

 

'instructions

 

On Error GoTo 0

 

ErrorSection:

 

MsgBox "Something went wrong"

 

End Sub

You can ensure that the error handling section can be accessed only in the event of an error by adding an Exit Sub statement above the section.

Sub Custom_Error_Handler()

 

On Error GoTo ErrorSection

 

'instructions

 

On Error GoTo 0

 

'exit before error handling section

Exit Sub

 

ErrorSection:

 

MsgBox "Something went wrong"

 

End Sub

You can resume the procedure on the line which caused the error by adding the Resume statement to the error handling section.

Sub Resume_At_Error_Line()

 

On Error GoTo ErrorSection

 

'instructions

 

On Error GoTo 0

 

'exit before error handling section

Exit Sub

 

ErrorSection:

 

MsgBox "Something went wrong"

 

'code to resolve the error

 

'return to the line which caused the error

Resume

 

End Sub

You can resume the procedure on the line after the one which caused the error by adding the Resume Next statement to the error handling section.

Sub Resume_After_Error_Line()

 

On Error GoTo ErrorSection

 

'instructions

 

On Error GoTo 0

 

'exit before error handling section

Exit Sub

 

ErrorSection:

 

MsgBox "Something went wrong"

 

'code to resolve the error

 

'return to the line after the error

Resume Next

 

End Sub

You can resume the procedure at any line by adding the Resume LineLabel statement to the error handling section.

Sub Resume_At_Specific_Line()

 

RestartPoint:

 

On Error GoTo ErrorSection

 

'instructions

 

On Error GoTo 0

 

'exit before error handling section

Exit Sub

 

ErrorSection:

 

MsgBox "Something went wrong"

 

'code to resolve the error

 

'return to the specified line label

Resume RestartPoint

 

End Sub

This page contains reference material for the code used in this module.

Something


 

There is currently no test for this module.

This page has 0 threads Add post