Click or drag to resize

HostFunctionstryCatch Method

Allows script code to handle host exceptions.

Namespace: Microsoft.ClearScript
Assembly: ClearScript.Core (in ClearScript.Core.dll) Version: 7.4.5
Syntax
public bool tryCatch(
	Object tryFunc,
	Object catchFunc,
	Object finallyFunc = null
)

Parameters

tryFunc  Object
A script function that invokes one or more host methods or properties.
catchFunc  Object
A script function to invoke if tryFunc throws an exception.
finallyFunc  Object  (Optional)
An optional script function that performs cleanup for the operation.

Return Value

Boolean
True if tryFunc completed successfully, false if it threw an exception that was handled by catchFunc.
Remarks
This function uses a try-catch-finally statement to invoke tryFunc. If an exception is thrown, it is caught and passed to catchFunc for analysis. If catchFunc returns false, the exception is rethrown. Regardless of the outcome, finallyFunc, if specified, is invoked as a final step before the function exits.
Example
The following code demonstrates handling host exceptions in script code. It assumes that an instance of ExtendedHostFunctions is exposed under the name "host" (see AddHostObject).
JavaScript
// import types
var ConsoleT = host.type("System.Console");
var WebClientT = host.type("System.Net.WebClient", "System");
// create a Web client
var webClient = host.newObj(WebClientT);
host.tryCatch(
    function () {
        // download Web document
        ConsoleT.WriteLine(webClient.DownloadString("http://cnn.com"));
    },
    function (exception) {
        // dump exception
        ConsoleT.WriteLine("*** ERROR: " + exception.GetBaseException().ToString());
        return true;
    },
    function () {
        // clean up
        ConsoleT.WriteLine("*** CLEANING UP ***");
        webClient.Dispose();
    }
);
See Also