The try-catch statements in Sling, like in other similar languages, are used for exception and error handling. The Sling implementation provides the following functionalities:

The regular try-catch statement

The regular try-catch statement syntax is as follows:

try {
	doSomething
}
catch(e as exception) {
	onError(e)
}

The parameter for the catch clause is optional and, if omitted, is assumed. The following code is equivalent to the previous:

try {
	doSomething
}
catch {
	onError(e)
}

Note that the e parameter continues to be available. Custom exception classes my also be used:

try {
	doSomething()
}
catch(exceptionObject as MyException) {
	onError(exceptionObject)
}

Multiple catch blocks are also supported:

try {
	doSomething()
}
catch(exceptionObject as MyException) {
	onError(exceptionObject)
}
catch(anotherExceptionObject as MyOtherException) {
	onError(anotherExceptionObject)
}

A finally block may also be included:

try {
	doSomething
}
catch {
	onError()
}
finally {
	PRINT "Execution of try/catch has ended"
}

The combined trycatch statement

Try trycatch statement is intended to be used as a shortcut for commonly used scenarios where the regular try-catch statements would have previously been used. The syntax works like this:

trycatch {
    doSomething()
}

And of course like always in Sling, a one-liner block can be shortened:

trycatch:
    doSomething()

And as a particular case of the trycatch keyword, a one-liner block can also be turned into a single statement:

trycatch doSomething()

All of the three samples above mean the same thing, and are all equivalent to the following:

try {
	doSomething()
}
catch(e as exception) {
	lang "java" {{{
		e.printStackTrace();
	}}}
	lang "cs" {{{
		System.Console.WriteLine(e.ToString());
	}}}
	lang "js" {{{
		console.log(e);
	}}}
}

The trycatch keyword can also be used as an expression. For example:

if not trycatch doSomething() {
    PRINT "Error took place"
    return false
}

Which, together with the assert statement, can be expressed also in a shorter format:

assert trycatch doSomething():
    PRINT "Error took place"

Additional reading


Twitter Facebook LinkedIn Youtube Slideshare Github