【发布时间】:2014-08-25 08:10:35
【问题描述】:
如果我在 c++ 中编写代码并抛出异常,我也可以捕获这些异常。示例;
int divide(int divison, int dividor)
{
if (dividor == 0)
throw DivideByZeroException();
return divison / dividor;
}
void main()
{
int a = 10,b=0;
try
{
result = divide(a, b);
cout << "result : " << result << endl;
}
catch (exception & e)
{
cout << e.what() << endl;
}
cout << "Enter a key to exit" << endl;
cin.get();
}
但是,如果我尝试直接捕获相同的异常程序崩溃。示例
void main()
{
int a = 10,b=0;
try
{
result = a / b;
cout << "result : " << result << endl;
}
catch (exception & e)
{
cout << "Normal exception :" << e.what() << endl;
}
cout << "Enter a key to exit" << endl;
cin.get();
}
为什么会发生这种情况?有没有办法在 c++ 中发生错误时阻止程序崩溃?
【问题讨论】:
-
DivideByZeroException 是一个继承自 std::exception 的类。
-
整数除法在 C++ 中也不例外。见[这里][1] [1]:stackoverflow.com/questions/6121623/…