在 C++ 中使用 Exception base class 导致应用程序崩溃
Usage of Exception base class in C++ is causing the app to crash
在下面的代码片段中,为什么如果我将 catch 语句包含在 "exception base class I get a app crash" 中(附上崩溃的图像)。
但是如果我使用
"const char* msg"
在 catch() 中它工作正常。
为什么异常库 class 导致应用程序崩溃?
double division(int a, int b)
{
if (b == 0)
{
throw "Division by zero condition!";
}
return (a / b);
}
main()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << "after division func" << endl;
cout << z << endl;
}
catch (const char* msg) { // WORKS FINE
//catch (exception& err) { // CAUSES the APP to crash![enter image description here][1]
cout << "INside catch for divide by 0" << endl;
}
除零条件不是由std::exception
导出的
您可以采取的一种解决方法是在代码中定义 catch all 语句
try {
z = division(x, y);
cout << "after division func" << endl;
cout << z << endl;
}
catch (exception& err) { // CAUSES the APP to crash![enter image description here][1]
cout << "INside catch for divide by 0" << endl;
}
catch(...) //include this in your code
{
cout<<"other exception occured";
}
你在这里抛出一个字符串文字:
throw "Division by zero condition!";
可以通过以下方式捕获:
catch (const char* msg)
然而,此异常并非源自 class std::exception
。如果你想要一个可以提供错误信息的,那么使用 std::runtime_error
.
throw std::runtime_error("Division by zero condition!");
...
catch (std::exception& err)
在下面的代码片段中,为什么如果我将 catch 语句包含在 "exception base class I get a app crash" 中(附上崩溃的图像)。
但是如果我使用
"const char* msg"
在 catch() 中它工作正常。
为什么异常库 class 导致应用程序崩溃?
double division(int a, int b)
{
if (b == 0)
{
throw "Division by zero condition!";
}
return (a / b);
}
main()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << "after division func" << endl;
cout << z << endl;
}
catch (const char* msg) { // WORKS FINE
//catch (exception& err) { // CAUSES the APP to crash![enter image description here][1]
cout << "INside catch for divide by 0" << endl;
}
除零条件不是由std::exception
导出的您可以采取的一种解决方法是在代码中定义 catch all 语句
try {
z = division(x, y);
cout << "after division func" << endl;
cout << z << endl;
}
catch (exception& err) { // CAUSES the APP to crash![enter image description here][1]
cout << "INside catch for divide by 0" << endl;
}
catch(...) //include this in your code
{
cout<<"other exception occured";
}
你在这里抛出一个字符串文字:
throw "Division by zero condition!";
可以通过以下方式捕获:
catch (const char* msg)
然而,此异常并非源自 class std::exception
。如果你想要一个可以提供错误信息的,那么使用 std::runtime_error
.
throw std::runtime_error("Division by zero condition!");
...
catch (std::exception& err)