【发布时间】:2013-07-13 18:54:58
【问题描述】:
我的操作系统是 Win8
使用 Code::Blocks 12.10
我正在尝试使用来自的
示例来处理抛出和处理异常
从 C++ 早期对象开始 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;
}
程序会编译,当我使用两个整数> 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.
我查看了其他示例,但还没有找到类似的代码来得出答案。
有什么建议吗?
【问题讨论】:
-
你有没有尝试捕捉
char const*? (只是一个疯狂的猜测) -
什么是“以下消息”?
-
我建议声明最接近首次使用的变量,并尽可能将它们初始化为它们的值。
-
该程序在 VC11 中运行良好。我得到异常消息作为输出。
-
@jrok - 在 C++11 之前,字符串字面量的类型隐式转换为
char*,因此对于 C++11 之前的编译器,代码是有效的。跨度>
标签: c++ exception try-catch throw