This project has moved. For the latest updates, please go here.

Raise a custom exception

Oct 7, 2014 at 5:29 PM
Hi ClearScripts,

I would like to raise an excpetion within the JavaScript code. For sure I may raise the Error object but I need to have something more specific. I didn't find out how to raise an .NET exception. Is there any way to do this?

Best regards,
Oct 8, 2014 at 3:53 PM
Hello, Torsten!

You can easily expose a function that throws a host exception. For example:
engine.Script.throwBadArg = new Action<string, string>((message, paramName) =>
    throw new ArgumentException(message, paramName);
Keep in mind that exceptions thrown in this manner are likely to be wrapped by ScriptEngineException by the time they reach the host, so you'll have to use InnerException or GetBaseException() to examine them.

On the other hand, if you need to catch and examine exceptions in JavaScript code, we recommend that you use JavaScript exceptions. Being normal JavaScript objects, they offer nearly infinite flexibility. That said, it is possible to catch and examine host exceptions in script code. See this thread for more information.

Good luck!
Oct 8, 2014 at 7:21 PM
Thanks for your answer!

As I see, I cannot
  • identify in the host application a JavaScript defined exception, like
function myException(message, 
{ = 'myException';
this.message = message + ' ' + id; = id;
myException.prototype = new Error();
myException.constructor = myException;
throw new myException('this is a message', 42);
I only get the ScriptEngineException with the message as text. And
  • identify within my JavaScript code the type of the CLR exception, like
try {
   throwBadArg('one', 'two');
catch (ex)
   if (ex instanceof ArgumentException)
      // ...
      // ...
(I added the type to the engine before executing code).

Is that right? I only want to be sure that I haven't overlooked something.

Best regards,
Oct 9, 2014 at 3:16 AM
That's correct.

ClearScript doesn't expose managed exceptions directly to script-based handlers. The best approach is to catch managed exceptions in managed code and pass them to script code for analysis. This thread includes sample code for doing so.

Similarly, it's best to catch script exceptions in script code and pass them to the host if necessary. You can find an example here.