September 20th, 2005

Catching Exceptions in JScript.NET

Heath Stewart
Principal Software Engineer

JScript.NET was created to be compatible with JScript while benefiting from and providing access to more robust features of the .NET Framework. If you’re accustomed to more oft-used managed languages like C# and VB.NET, catching different types of exception classes should be no stranger. Considering JScript.NET, however, what would you expect to be printed from the code below?

import System;
try
{
  throw new Exception("Error: something bad happened.");
}
catch (e)
{
  if (e instanceof Exception)
    print(e);
}

If you said nothing then you’re correct. Exceptions are wrapped in an Microsoft.JScript.ErrorObject that does not extend System.Exception. You need to extract the exception from the ErrorObject if you’d like to handle different classes of exceptions. One way to do this is using a public static method that JScript.NET uses to throw exceptions for types other than Exception and ErrorObject.

import System;
import Microsoft.JScript;
try
{
  throw new Exception("Error: something bad happened.");
}
catch (e)
{
  var ex = Throw.JScriptThrow(e);
  if (ex instanceof Exception)
    print(e);
}

You can also call the explicit cast operator defined for the ErrorObject class, but make sure you’re dealing with an ErrorObject first in case another type is being thrown because the castclass IL instruction is used to cast the exception variable to ErrorObject.

import System;
import Microsoft.JScript;
try
{
  throw new Exception("Error: something bad happened.");
}
catch (e)
{
  if (e instanceof ErrorObject)
  {
    var ex : Exception = ErrorObject.op_Explicit(e);
    if (ex)
      print(e);
  }
}
Topics
Script

Author

Heath Stewart
Principal Software Engineer

Heath is an application architect and developer, looking to help educate others to learn professional development. Besides designing and developing applications he enjoys writing about intermediate and advanced topics. Heath also consults for deployment packages and scenarios within Microsoft and for external customers.

0 comments

Discussion are closed.