Exceptions: Difference between revisions

Content deleted Content added
→‎Throwing Exceptions: {{Lines_too_long}}
vba
Line 1,070: Line 1,070:
End Try
End Try
End Sub</lang>
End Sub</lang>

=={{header|Visual Basic for Applications}}==

For historical reasons, Exceptions are called 'Errors' in VBA and VB Classic.
VBA inherited several distinct exception handling models, which may be freely mixed and matched.
The major limitations are that nested Try/Catch blocks must be constructed by the user, and that the User Defined Labels required for the Catch/Finally blocks may not be reused within a subroutine. For these reasons, it is conventional to only have only 1 Try/Catch block per subroutine.

===Throw exceptions===
<lang vba>Sub foo1()
err.raise(vbObjectError + 1050)
End Sub

Sub foo2()
Error vbObjectError + 1051
End Sub
</lang>

===Catching exceptions===
<lang vba>Sub bar1()
'by convention, a simple handler
On Error Goto Catch
fooX
Exit Sub
Catch:
'handle all exceptions
Exit Sub

Sub bar2()
'a more complex handler, illustrating some of the flexibility of VBA exception handling
on error goto catch
100 fooX
200 fooY
'finally block may be placed anywhere: this is complexity for it's own sake:
goto finally

catch:
if erl= 100 then
' handle exception at first line: in this case, by ignoring it:
resume next
else
select case err.nummber
case vbObjectError + 1050
' handle exceptions of type 1050
case vbObjectError + 1051
' handle exceptions of type 1051
case else
' handle any type of exception not handled by above catches or line numbers
resume finally

finally:
'code here occurs whether or not there was an exception
'block may be placed anywhere
'by convention, often just a drop through to an Exit Sub, rather tnan a code block
Goto end_try:

end_try:
'by convention, often just a drop through from the catch block
exit sub


{{omit from|M4}}
{{omit from|M4}}