简体   繁体   English

C ++,Java和JavaScript异常处理有什么区别?

[英]What is the difference between C++, Java and JavaScript exception handling?

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. 我也问这个问题,因为我注意到与JavaScript版本相比,C ++异常处理似乎非常慢。

我在这个页面上找到了关于异常处理和性能/实现的最详细的答案: http//lazarenko.me/tips-and-tricks/c-exception-handling-and-performance

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 我只知道C ++异常处理的基础知识,但据我所知,Java有异常的基于Object的层次结构( ThrowableExceptionRuntimeExceptionError ),而在C ++中你可以做

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 ). 这个看似微小的差异引入的其他差异是C ++实际上只有Java世界中的运行时异常,这意味着您可以随时抛出任何内容而无需显式编写代码来处理throw伪异常( 我是不愿意调用int或任何其他原始类型的异常,它们可能只是异常值 )。

Lastly, due to their nature when compared to Java's exceptions C++ exceptions don't by default contain anything comparable to Java's stacktraces. 最后,由于与Java的异常相比它们的性质,C ++异常默认情况下不包含与Java的堆栈跟踪相当的东西。

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. 一种方法(我认为C ++和Java使用,我不知道Javascript),是维护一堆错误处理程序。 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). 抛出异常时,顶部条目将从堆栈中弹出并相应地处理异常,或者如果无法处理它,则从堆栈中弹出另一个条目(例如,当顶部处理程序为OutOfBoundException时,它会收到NullPointerException)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM