错误:抛出“ char const *”实例后终止调用
要求终止应用程序运行时以异常方式终止它。请与应用程序的支持团队联系。
我不确定执行此操作时是什么导致编译器崩溃。有任何想法吗?编程新手。
#include <iostream>
#include <iomanip>
using namespace std;
//Template for Maximum
template <class X>
X Maximum(X arg1, X arg2)
{
if (arg1 > arg2)
return arg1;
else
return arg2;
}
//Template for Minimum
template <class M>
M Minimum(M arg1, M arg2)
{
if (arg1 > arg2)
return arg2;
else
return arg1;
}
/* Template for Divide(D arg1, D arg2) arg1: the dividend arg2: the divisor Description:
Divides arg1 by arg2. If arg2 equals zero then an exception is thrown. */
template <class D>
D Divide(D arg1, D arg2)
{
if (arg2 == 0) {
throw "You cannot devide by zero! ";
}
return (arg1 / arg2);
}
int main()
{
int a, b;
float c, d;
double e, f;
a = 2;
b = 22;
cout << setprecision(4) << fixed << showpoint << "min:" << Minimum(a, b) << "\tmax: " << Maximum(a, b) << endl;
c = 4.7f;
d = 2.97f;
cout << setprecision(4) << fixed << showpoint << "min:" << Minimum(c, d) << "\tmax: " << Maximum(c, d) << endl;
e = 387.78;
f = 387.7798;
cout << setprecision(4) << fixed << showpoint << "min:" << Minimum(e, f) << "\tmax: " << Maximum(e, f) << endl;
e = 40;
f = 0;
try {
cout << setprecision(4) << fixed << showpoint << "Divide: " << e << '/' << f << " = " << Divide(e, f) << endl;
}
catch (string exceptionString) {
cout << exceptionString;
}
system("pause");
return 0;
}
字符串文字不是std::string
。您抛出前者,但尝试抓住后者。尽管事实上astd::string
可能是从字符串文字构造的,但不会在catch子句中发生。catch子句中允许的转换在[except.handle] / 3中进行了详细说明:
如果满足以下条件,则处理程序将匹配类型E的异常对象:
- 处理程序的类型为cv T或cv T&,并且E和T是同一类型(忽略顶级cv限定词),或者
- 处理程序是cv T或cv T&类型,并且T是E的明确公共基类,或者
- 处理程序的类型为cv T或const T&,其中T是成员类型的指针或指针,E是成员类型的指针或指针,可以通过以下一种或多种方式将其转换为T
- 标准指针转换,不涉及对私有类,受保护类或歧义类的指针的转换
- 函数指针转换
- 资格转换,或
- 处理程序的类型为cv T或const T&,其中T是指向成员类型的指针或指针,E是std :: nullptr_t。
而且这两个都不适用于文字->std::string
转换的情况。
最终导致该异常未被捕获,并且运行时调用std::terminate
应以未捕获的异常发生。
通常,最好抛出一个专用的异常类型(它可能是层次结构的一部分),以便该类型名称可以传达发生的错误。如果需要编写一个处理程序(或一组处理程序),这将允许以更可靠的方式处理错误。
如果由于某种原因不想遵循标准惯例,则必须使转换成为上述项目符号中提到的转换之一。您可以:
std::string
文字,如"You cannot devide by zero!"s
(注意s
后缀)。const char*
。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句