views:

114

answers:

2

They are very different kind of languages and the way they handle exceptions might be rather different.. How is exception handling implemented and what are the implementation difference within these languages?

I am asking this question also because I noticed that C++ exception handling seems to be very slow compared to the JavaScript version.

+1  A: 

I know just the basics of C++ exception handling but as far as I can see, Java has excplicit Object-based hierarchy for exceptions (Throwable, Exception, RuntimeException, Error) while in C++ you can do

try
{
     throw 1337;
}
catch (int i)
{
    // i == 1337
}

This of course reflects to the design of your class structures and general exception handling policies etc.

Other difference introduced by this seemingly minor difference is that C++ really only has what would be known as Runtime Exceptions in Java world, which means that you can throw anything at any time without explicitly writing code to handle the throw pseudo-exception (I'm not willing to call int or any other primitive type an exception, they're just possibly exceptional values).

Lastly, due to their nature when compared to Java's exceptions C++ exceptions don't by default contain anything comparable to Java's stacktraces.

Esko
It is recommended though in C++ to use classes that derive from std::exception
Nikko
in JavaScript too, you can throw anything (besides the pre-defined Error objects). it’s just a question, how useful that is.
Dormilich
+1  A: 

If you're asking about how it internally generates these exceptions, then it's a pretty complex issue.

One approach (that I think C++ and Java use, I dont know about Javascript), is to maintain a stack of error handlers. When an exception is thrown, the the top entry is popped off the stack and handles the exception appropriately or pops another entry from the stack if it can't handle it (such as it received a NullPointerException when the top handler is a OutOfBoundException).

samoz
This strategy (a handler stack) is not used by any Java implementation that I've heard of.
Stephen C