我在抛出/捕获自定义异常时遇到问题。
背景:我正在建立一个房产(如房地产)经理,将房产,租户,银行账户和交易作为类存储,并根据合同将它们合并。
每个交易都是双向链接列表下的节点。
我正在将事务构造函数nullptr
作为in_tnumber
提供给它,看看它会做什么。
这是交易类:
// manager is a namespace that is used for the entire program
// Each transaction will be stored as a node on a doubly linked list
class transaction
{
public:
transaction(const char *in_tnumber,
const int &in_amount,
manager::transaction *in_head)
throw(std::bad_alloc, manager::pexception);
~transaction()
// Other functions...
private:
// Links for the list.
manager::transaction *head;
manager::transaction *tail;
// Transaction number
char *tnumber;
// Transaction amount
int tamount;
char *remarks
};
transaction::transaction(const char *in_tnumber,
const int &in_amount,
manager::transaction *in_head)
throw(std::bad_alloc, manager::pexception)
{
if ((in_tnumber == nullptr) || (in_tnumber[0] == '\0'))
throw manager::pexception("Transaction number cannot be empty ");
if (in_tamount <= 0)
throw manager::pexception("Transaction amount cannot be empty ");
tnumber = new char[strlen(in_tnumber) + 1];
strcpy(tnumber, in_tnumber);
tamount = in_tamount;
remarks = nullptr;
tail = nullptr;
}
transaction::~transaction()
{
delete [] tnumber;
delete [] remarks;
}
我也有一个类似的异常类
class pexception
{
public:
pexception(char *in_message);
~pexception() { delete [] message; }
char* get_message() const { return message; }
private:
char *message;
};
pexception::pexception(const char *in_message)
{
message = new char[strlen(in_message) + 1];
strcpy(message, in_message);
}
当transaction
构造函数抛出异常时,我得到了这个:
交易号不能为空
退出...
/ storage / dimos / projects / build-soft_dev_sat_Mk_III-Debug / soft_dev_sat_Mk_III&#39;:双重释放或损坏(fasttop):0x00000000006f60c0
和Qt Creator说程序崩溃了。
main()看起来像这样
int main()
{
try {
transaction test("", // As opposed to "1234567890" or something like that
300,
nullptr);
cout << "Tnumber: " << test.get_tnumber();
}
catch(manager::pexception e)
{
cout << e.get_message();
cout << "\nEXITING...\n";
return -1;
}
return 0;
}
我在命令行(debian)我该如何解决这个问题? 当in_tnumber被填入并且没有时,它工作正常 抛出异常。
感谢您的回答。抱歉,长代码。