| 1 | = Throw = |
| 2 | |
| 3 | The '''throw''' statement is used to signal the occurrence of an anomalous situation (exception) during the program execution. |
| 4 | |
| 5 | The thrown exception is an object whose class is derived from System.Exception, for example: |
| 6 | {{{ |
| 7 | class MyException inherits System.Exception |
| 8 | pass |
| 9 | # ... |
| 10 | throw MyException() |
| 11 | }}} |
| 12 | |
| 13 | Usually the throw statement is used with try-catch-finally statements. |
| 14 | |
| 15 | You can also rethrow a caught exception using the throw statement by specifying the caught exception |
| 16 | {{{ |
| 17 | catch exc as MyException |
| 18 | if passOn |
| 19 | throw exc # rethrow caught exception |
| 20 | # ... |
| 21 | }}} |
| 22 | |
| 23 | == Grammar == |
| 24 | {{{ |
| 25 | throw EXCEPTION_OBJECT |
| 26 | }}} |
| 27 | |
| 28 | == Example == |
| 29 | {{{ |
| 30 | class ThrowTest |
| 31 | def getNumber(index as int) as int |
| 32 | nums = [ 300, 600, 900 ] |
| 33 | if index > nums.length |
| 34 | throw IndexOutOfRangeException() |
| 35 | return nums[index] |
| 36 | |
| 37 | def main is shared |
| 38 | result = ThrowTest.getNumber(3) |
| 39 | |
| 40 | /# |
| 41 | Output: |
| 42 | The System.IndexOutOfRangeException exception occurs. |
| 43 | #/ |
| 44 | }}} |