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 ; }

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".

If the finally clause is used it MUST be on the same line as the closing brace for the catch clause.
For example this syntax is excepted
try 
{ command ; }
catch X {
	command ; 
} finally
{
	command;
}


But this is not and will generate a syntax error
try { command ; } catch X { command ; } 
finally { command }		## SYNTAX ERROR HERE



Example
try {
	if !  command ; then
		throw "Failed command" 
		echo Should Not happen
	fi
	command2 ;
	
}  
catch X 
{
	echo Error: $X
	
}  finally 
{
	echo Completed block
}


Result
command: not found
Error: Failed command
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. The finally block is executed whether or not an exception was caught. 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
There are no comments on this page.
Valid XHTML :: Valid CSS: :: Powered by WikkaWiki