Wednesday, May 23, 2007

More on JScript exceptions

I don't know much about JScript, so when I need to find out anything I head off to Google. So that's what I did when I wanted to know about throwing exceptions. Almost every example I've seen shows something like - 

throw "something went wrong";

Initially I thought this would be wrapped up as an exception by the JScript runtime, but it turns out it is actually a string that gets thrown. Which may be fine in some cases. The problem comes when you want to catch exceptions. If you want to catch all exceptions thrown in a bit of code (yeh I know, bad idea, but this is JScript not software engineering...) then things will get complicated. The runtime will throw exceptions but your own code is throwing strings, so you have to deal with them differently. Turns out the solution is pretty straighforward -

throw new Error("something went wrong");

Now everything is an exception and life is good.

As a side note, I've not considered throwing anything other than an exception before. C# doesn't allow it, although I guess IL probably does since it needs to support JScript.NET. Delphi partially allows it, you can throw any object you like but not strings since they aren't proper objects in the Delphi world. But it's not clear to me why you'd ever want/need to do it...

No comments: