【问题标题】:Unusual termination in try catch throwtry catch throw 中的异常终止
【发布时间】: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


【解决方案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*

handler (catch) 捕获了哪些类型在 [except.handle]/3 中进行了描述,并且没有一种情况适用于此,即 const char* 未被捕获char* 类型的 处理程序

【讨论】:

  • 这对 C++11 是正确的;在 C++11 之前,存在从字符串文字到 char* 的隐式类型转换,并且代码是有效的。
  • 是的,它已被弃用,但这并不意味着它不是该语言的一部分。已弃用意味着可能在未来消失。不推荐使用 C 样式的标头,但它们永远不会消失,尽管在标准化早期有一些人的幻想。
  • 是的,我并不是说不允许这样做。它只是应该避免使用它,即使它在 C++03 中仍然是合法的。
  • 是的;如果没有const,我永远不会写那个 catch 子句。
  • @PeteBecker 在进一步研究 C++03 标准后,从 array 到 n const charpointer to char,而不是指针转换?
猜你喜欢
  • 2010-12-14
  • 1970-01-01
  • 2011-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多