我的操作系统是Win8
使用Code :: Blocks 12.10
我正试图通过一个例子来处理抛出和处理异常 从C ++ Early Objects开始,Addison Wesley。
以下是我正在使用的简单代码:
// This program illustrates exception handling
#include <iostream>
#include <cstdlib>
using namespace std;
// Function prototype
double divide(double, double);
int main()
{
int num1, num2;
double quotient;
//cout << "Enter two integers: ";
//cin >> num1 >> num2;
num1 = 3;
num2 = 0;
try
{
quotient = divide(num1,num2);
cout << "The quotient is " << quotient << endl;
}
catch (char *exceptionString)
{
cout << exceptionString;
exit(EXIT_FAILURE); // Added to provide a termination.
}
cout << "End of program." << endl;
return 0;
}
double divide(double numerator, double denominator)
{
if (denominator == 0)
throw "Error: Cannot divide by zero\n";
else
return numerator/denominator;
}
程序将编译,当我使用两个整数&gt; 0执行正常。如果我尝试除以0,我得到以下消息:
terminate called after throwing an instance of 'char const*'
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
Process returned 255 (0xFF) execution time : 4.485 s
Press any key to continue.
我已经查看了其他示例,但尚未找到类似的代码来从中获取答案。
有什么建议吗?
答案 0 :(得分:1)
C ++标准中有一个引人注目的例子,[except.throw] / 1:
示例:
throw "Help!";
可以被
const char*
类型的处理程序捕获:try { // ... } catch(const char* p) { // handle character string exceptions here }
当您通过throw "Error: Cannot divide by zero\n";
投掷时,throw
之后的表达式是字符串文字,因此类型数组n const char (其中 n 是字符串+ 1)的长度。此数组类型将衰减为指针[except.throw] / 3,因此抛出的对象类型为char const*
。
处理程序(catch
)捕获了哪些类型在[except.handle] / 3中描述,并且这里没有一个案例适用,即const char*
没有被char*
类型的处理程序捕获。