在QT中创建我自己的异常并在函数中抛出异常

myExcption.h

#ifndef MYEXCEPTION_H 
#define MYEXCEPTION_H 

#include <qtconcurrentexception.h> 
#include <QDebug> 

class MyException: public QtConcurrent::Exception 
{ 
public: 
    void raise() const {qDebug() << "\nException: "; throw *this;} 
}; 

#endif // MYEXCEPTION_H 

现在目前我怎么扔豁免是这样的:

myFuction.h

void Commands(QString Command_in, MyException &wrongInput); 

myFunction.cpp

void Command(QString Command_in, MyException &wrongInput) 
{ 
    if(Command_in != "some string") 
    { 
     wrongInput.raise(); 
    } 
} 

的main.cpp

String s = "some String"; 
MyException wrongString; 
try 
{ 
    Command(s, wrongString); 
} 
catch(MyException &wrongString) 
{ 
    qDebut << "String invalid"; 
} 

现在这个工作,但我觉得我不应该在我的例外每一个引用传递功能。我有什么选择?这是我觉得我应该能够做到的,但我不知道该怎么做。

myFunction.cpp

void Command(QString Command_in) 
{ 
    if(Command_in != "some string") 
    { 
     throw myException; 
    } 
} 

的main.cpp

QString s = "some String"; 
try 
{ 
    Command(s); 
} 
catch(MyException &wrongString) 
{ 
    qDebut << "String invalid"; 
} 

A

回答

2

你快到了。在throw声明中,通常会引发异常类的临时对象。例如。

void Command(QString Command_in) 
{ 
    if(Command_in != "some string") 
    { 
     throw MyException{}; 
    } 
} 

从技术上讲,有什么不对的命名对象的,但它是一个线长,而不是更具可读性:

void Command(QString Command_in) 
{ 
    if(Command_in != "some string") 
    { 
     MyException someRandomName; 
     throw someRandomName; 
    } 
} 

当然,这意味着你不需要raise()方法无论是。但如果你想要一个,它应该是static

class MyException: public QtConcurrent::Exception 
{ 
public: 
    static void raise() const {qDebug() << "\nException: "; throw MyException{};} 
}; 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蝈蝈(GuoGuo)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值