Try...Catch: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
|||
Line 53: | Line 53: | ||
[[Category:Language Reference]] | [[Category:Language Reference]] | ||
[[Category:Statements - Flow of control]] |
Revision as of 22:25, 13 September 2012
Try
- {statements}
- Throw errCode
- {statements}
Catch err
- {statements}
- {statements}
[Finally
- {statements}]
- {statements}]
End Try
Description
The Try…Catch statement allows you to test a block of code for runtime errors. The Try block contains the code to be run, and the Catch block contains the code to be executed if an error occurs. The optional Finally block is executed whether there is an error or not.
An error can be created by something that gets executed (such as division by zero) or you can force an error using the Throw statement. When you force an error using Throw, supply an errCode which can be a number or a string.
The Catch block has the value of the runtime error or the Throw message you supplied in err.
Example
Rem Try Example 'Try catches run time errors Try Dim CurrLiab, CurrAssets CurAssets=InputBox("Enter assets") If Not IsNumeric(CurAssets) Then Throw 1 If CurAssets < 0 Then Throw "lessthan" CurLiab=InputBox("Enter liabilities") If CurLiab=0 Then Throw "Divide by Zero" If CurLiab < 0 Then Throw "Liabilities must be > 0" End If If Not IsNumeric(CurLiab) Then Throw 1 Print CurAssets, CurLiab Print "Ratio:" & CurAssets/CurLiab Catch err If err=1 Then err="Enter a number" If err="lessthan" Then err="Value must be >= 0" End if Print err Finally 'this is optional Print "Done" End Try
Output
(depends on what values are input) Done