| 1 | = Try-Catch-Get Expression = |
| 2 | |
| 3 | The try expression provides a simple way to run a single expression that may generate a single exception Type |
| 4 | and provide a default value if it does so. |
| 5 | |
| 6 | It's a convenience for a [wiki:Try try-catch] statement for a single statement which would assign the expression.[[BR]] |
| 7 | |
| 8 | The value of the expression is the value of the expression following 'try' or if an exception is thrown the value of the expression after the 'get'. |
| 9 | |
| 10 | If an Exception-Type is not given it will catch all Exceptions. |
| 11 | |
| 12 | == Grammar == |
| 13 | try <expr> catch [ <Exception-Type> ] get <expr> |
| 14 | |
| 15 | |
| 16 | == Examples == |
| 17 | |
| 18 | {{{ |
| 19 | #!cobra |
| 20 | inVal = '..' #an int string presumably |
| 21 | x = try int.parse(inVal) catch FormatException get 0 # return 0 if inVal not an int String |
| 22 | |
| 23 | # Catch all exceptions |
| 24 | dflt = '---' |
| 25 | s1 = try String.format('{1:P}', 0.123) catch get dflt |
| 26 | assert s1 == '---' |
| 27 | |
| 28 | name = try .input('Enter your name:') catch ConsoleInputException get 'ERROR' |
| 29 | }}} |
| 30 | |