Revision [813]
This is an old revision of ExceptionHandling made by DavidLee on 2009-09-30 06:17:10.
Exception Handling
xmlsh supports the Java style syntax for exception handling. Currently the only exceptions that are supported are the exceptions generated by the throw command. Native java exceptions generated within command are trapped at the completion of that command, printed on stderr, and converted to a -1 exit status.
The syntax for a try/catch block is as follows
try { list ; } catch word { list ; }
try { list ; } catch word { list ; } finally { list ; }
If the finally clause is used it MUST be on the same line as the closing brace for the catch clause.try { list ; } catch word { list ; } finally { list ; }
In order to raise an exception the throw command must be used
throw expression
The expression can be any type and it is passed to the catch clause as the value of the variable "word".
Examples
try { if ! command ; then throw "Failed command" fi command2 ; } catch X { echo Error: $X } finally { echo Completed block }
Exceptions can be thrown out of functions, sub shells and sub scripts. Try/catch blocks can be nested both within the same shell and within sub shells and scripts. Within the catch block an exception can be rethrown or a new exception thrown. As in java, the finally clause (if present) is executed in each nested try/catch block if an exception is raised within the catch clause.
try { try { throw <[ <fail>element</fail> ]> } catch E1 { echo Caught inner throw $E1 throw $E1 } finally { echo Finally inner block ; } } catch E2 { echo Caught outer throw $E2; } finally { echo Finally outer block ; }
Results
Caught inner throw <fail>element</fail> Finally inner block Caught outer throw <fail>element</fail> Finally outer block
CategoryCommands
BasicSyntax