gpt4 book ai didi

c++ - try catch throw 异常终止

转载 作者:太空宇宙 更新时间:2023-11-04 11:52:16 26 4
gpt4 key购买 nike

我的操作系统是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;
}

程序会编译,当我使用两个 int > 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.

我看过其他例子,但还没有找到类似的代码来得出答案。

有什么建议吗?

最佳答案

C++ 标准中有一个引人注目的示例,[except.throw]/1:

Example:

throw "Help!";

can be caught by a handler of const char* type:

try {
// ...
} catch(const char* p) {
// handle character string exceptions here
}

当您通过 throw "Error: Cannot divide by zero\n"; 抛出时,throw 之后的表达式是字符串文字,因此类型为 array n 个 const char(其中 n 是字符串的长度 + 1)。此数组类型已衰减为指针 [except.throw]/3,因此抛出的对象类型为 char const*

handler 捕获哪些类型(catch)在 [except.handle]/3 中有描述,这里没有任何情况适用,即 const char* 未被 char* 类型的处理程序 捕获。

关于c++ - try catch throw 异常终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17633252/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com