gpt4 book ai didi

c++ - 如何在 C++ 中捕获 'any' 异常?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:24:27 24 4
gpt4 key购买 nike

据我了解,c++ 中的所有异常最终都会扩展exception。在 Java 世界中,无论异常的类型如何,捕获 Exception e 都会起作用。这是如何在 C++ 中完成的?

为什么在这个片段中没有捕获到异常?

try{        
int z = 34/0;
cout << "This line should not appear" << endl;
} catch (exception e) {
cout << "An error has occurred: " << e.what(); // Not executed
}

另外,在 C++ 中,如何找出哪些操作导致了哪些异常?

最佳答案

Why is that in this snippet exception is not caught?

整数除以 0 不是标准的 c++ 异常。因此在这种情况下不会抛出异常,您得到的是普通的未定义行为

某些特定的编译器可能会将这种情况映射到特定的异常,您将不得不检查编译器文档以找到相同的情况。但是,使用此类功能将是不可移植的,并且您的代码将仅限于您的特定编译器。

在这种情况下,您能做的最好的事情就是自己检查错误条件(除数等于零)并明确抛出异常。

Also, in C++, how can one find out what actions causes what exception?

std::exception 类专门为此提供了一个方法std::exception::what()

关于c++ - 如何在 C++ 中捕获 'any' 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12170584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com