I’m starting to learn JavaScript, so far no problem but I have a hard time finding a good explanation of the Exception mechanism in JS.
It seems similar to C++, JS allows to throw about every object, instead of just throwing an Exception object (probably due to it’s dynamic nature).
throw 'An error occured.';
works, as well as
throw new Exception('An error occured.');
catch and finally both seem to work like their Java equivalent. Still, I don’t know what are widely accepted best practices regarding exceptions.
So, for example, is it legit to throw objects of type string, like:
throw 'An error occured';
How would I differentiate between different types of exceptions?
Throwing and catching exceptions is pretty expensive, and with JavaScript, you’re primarily going to get exceptions in cases like when you try to parse a JSON string that is malformatted. I would suggest avoiding try/catch as much as possible and instead focus on checking for errors the old fashion way (return types, making sure variables are properly initialized before using them, etc.) since exceptions are less likely to happen here than in C++ or especially Java or .NET.
Andy E’s recommendation is a good one for actually handling them, but in general, you should try to write JavaScript code defensively so that you don’t even need try/catch. Remember, even JITed JavaScript in Chrome (fastest engine) is still slow as heck compared to Java or C#, to say nothing of C++, so anything that is expensive in those languages is likely to be even more so in JavaScript.