Revision [815]

This is an old revision of ExceptionHandling made by DavidLee on 2009-09-30 06:20:32.

 

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.
For example this syntax is excepted
try 
{ command ; }
catch X {
	command ; 
} finally
{
	command;
}


But this is not

try { command ; } catch X { command ; } 
finally { command }


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

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
q
There are no comments on this page.
Valid XHTML :: Valid CSS: :: Powered by WikkaWiki