我似乎无法在C ++中捕获此异常

问题描述

由于某种原因,在测试异常处理时执行该程序时会退出。这是im用作异常接收者的类

Error in file(file,"rt") : cannot open connection

这是另一个生成异常的类的函数成员

#ifndef _BADALLOC
#define _BADALLOC
#include <cstring>
using namespace std;
class badalloc{
private:
    char* Message;
    double Number;
    
public:
    explicit badalloc(char* M="Error",const int & N=0)  {strcpy(Message,M); Number=N;}
    char* what () const {return Message;}
};
#endif

主要测试:

void ContoCorrente::Prelievo ( const double & P) throw ( badalloc )
{
if(P>0)
{ 
    throw (badalloc ("ERROR 111XX",P));
} ...

输出


进程在1.276秒后退出,返回值3221225477 按任意键继续 。 。

我尝试将badalloc对象定义为“ const”,但没有用。有什么想法吗?

解决方法

非常简单,您正在复制到Message类中的未初始化指针badalloc

仅通过构造一个badalloc对象就会收到此错误。这与异常无关。

编辑

使用std::string来避免指针问题是一种可能的解决方案。

#ifndef _BADALLOC
#define _BADALLOC

#include <string>

class badalloc{
private:
    std::string Message;
    double Number;
    
public:
    explicit badalloc(const char* M="Error",const int & N=0) : Message(M),Number(N) {}
    const char* what () const {return Message.c_str();}
};

#endif