【问题标题】:Exceptions on c++C++ 的异常
【发布时间】:2020-06-21 18:19:41
【问题描述】:

我有这个:

// exception::what
#include <iostream>       // std::cout
#include <exception>      // std::exception


struct ooops : std::exception {
 const char* what() const noexcept {return "Ooops!\n";}
};


class A: std::exception{
  public: 
    int tt;
    int getTT(int rr){
      if (rr ==5) throw ooops();
      return rr;
    };  
};

int main () {
 try {
   A testA;
   int ww = testA.getTT("kkk");
   std::cout << ww << std::endl;//throw ooops();
 } catch (std::exception& ex) {
  std::cout << ex.what();
 }
 return 0;
}

我想用上面的字符串调用getTT(),我想抛出我的异常消息而不是默认消息。我知道如果我从 Exception 类中重载一个方法,我会没事的,但我想问是否有更简单的方法来做到这一点。我正在阅读有关 Exceptions 的文档,但我找不到有用的东西。

【问题讨论】:

  • “我想用字符串调用getTT()” getTT() 接受一个整数,而不是一个字符串。 “而不是默认的” 你是什么意思?没有“默认例外”之类的东西。您可以抛出任何类型的对象。总而言之,不清楚您要的是什么。
  • 老实说,我不明白你打算做什么.. 请解释一下你想要什么
  • 为什么A继承自std::exception?

标签: c++ exception methods overloading


【解决方案1】:

你可以扔任何物体。你不必继承std::exception

#include <iostream>
class A{
public:
    int tt;
    int getTT(int rr){
        if (rr ==5) throw "ooops";
        return rr;
    };
};

int main () {
    try {
        A testA;
        int ww = testA.getTT(5);
        std::cout << ww << std::endl;//throw ooops();
    } catch (const char* exc) {
        std::cout << exc;
    }
    return 0;
}

如果不知道异常的类型,可以使用...,如下

#include <iostream>
class A{
public:
    int tt;
    int getTT(int rr){
        if (rr ==5) throw "ooops";
        return rr;
    };
};

int main () {
    try {
        A testA;
        int ww = testA.getTT(5);
        std::cout << ww << std::endl;//throw ooops();
    } catch (...) {
        std::cout << "exception has been thrown";
    }
    return 0;
}

【讨论】:

    【解决方案2】:

    您的ooops 类应派生自 std::runtime_error 相反,它将用户定义的字符串作为输入并覆盖 what() 以便您返回该字符串。

    您的代码中还有其他错误。 A 不应派生自 std::exception。而A::getTT() 将int 作为输入,但您尝试将字符串文字(const char[4])传递给它。

    试试这个:

    #include 
    #include 
    #include 
    
    结构 oops : std::runtime_error {
        哎呀(常量标准::字符串&what_arg =“哎呀!”)
            : runtime_error(what_arg)
        {
        }
    };
    
    A类{
    上市:
        诠释 tt;
        int getTT(int rr) 常量 {
            if (rr == 5) throw ooops("rr 不能是 5");
            返回 rr;
        }
    };
    
    诠释主要(){
        尝试 {
            一个测试A;
            int ww = testA.getTT(5);
            std::cout 
        

    【讨论】:

      猜你喜欢
      • 2012-06-17
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 2015-07-28
      • 2017-06-16
      相关资源
      最近更新 更多