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); } }
0 comments