【问题标题】:Throw and catch std::string抛出并捕获 std::string
【发布时间】:2014-04-26 21:33:38
【问题描述】:

我编写了奇怪的代码,但令人惊讶的是它可以工作。但现在我不知道我扔的是什么,我怎么能抓住它:

class Date {
private:
    int day;
    int month;
    int year;
    int daysPerMonth[];
public:
    Date( int day, int month, int year ) {
        int daysPerMonth[12] = {31,28,31,30,31,30,31,31,30,31,30,31};

        if(isValidDate(day, month, year)) {
            this->day = day;
            this->month = month;
            this->year = year;
        } else {
            throw std::string("No valid input date numbers...");//what i throw???
        }
    }

请帮我写代码。

【问题讨论】:

  • 您想了解什么?该代码应该做什么?
  • 你正在抛出 std::string(),通过const std::string& 或通过值std::string 捕获。希望你不是拖钓:-)
  • “我编写了奇怪的代码,但令人惊讶的是它的工作原理”-> 这太棒了,我把它放在我的报价单上.
  • 如果您抛出 std::runtime_error,那么父代码可以捕获 std::exception 并获取您的异常,而无需仅为您的代码添加额外的异常处理程序。

标签: c++ string class throw


【解决方案1】:

你可以像下面这样使用(未编译):-

class Date {
private:
int day;
int month;
int year;
int daysPerMonth[];
public:
Date( int day, int month, int year ) {
    int daysPerMonth[12] = {31,28,31,30,31,30,31,31,30,31,30,31};

    if(isValidDate(day, month, year)) 
    {
        this->day = day;
        this->month = month;
        this->year = year;
    } else {
        throw std::string("No valid input date numbers...");//what i throw???
        }
    }
};

int main()
{
 try{
    Date d(55,223,0122);
  }
 catch(std::string &e)
 {
    // Do necessary handling
  }
}

【讨论】:

    【解决方案2】:

    在 C++ 中,您可以抛出任何类型的对象。通常是std::exception 或从它派生的类型,但它可以是其他任何东西。例如 MFC 中的 CException_com_errorstd::exception 无关。无论你扔什么,你都必须抓住同样的东西。 (你不能抛出 std::string 并抓住 std::exception。)

    【讨论】:

      【解决方案3】:

      C++ 允许您throw 任何类型(包括基本类型)的值。

      try {
          throw 42;
      } catch(int e) {
          std::cout << "Caught: " << e << "\n";
      }
      

      但与 C++ 中的许多其他事情一样,仅仅因为您可以做到,并不意味着您应该这样做。

      这里的usual advice 是以某种方式抛出从std::exception 派生的专用异常对象。也就是说,如果抛出的类型不应该在其他上下文中使用。如果要将某个值与异常相关联,请构建一个包含该值作为成员的异常包装类,而不是直接抛出该值的类型。

      这个建议的基本原理是你想建立一个异常层次结构,允许在不同层次的一般性上捕获:如果我对确切的异常类型不感兴趣,我只捕获std::exception;如果我只想处理某些类型的错误,我会在异常层次结构中进一步捕获派生类。

      如果您将异常类型与程序中使用的其他类型区分开来,则此类异常层次结构更易于维护和推理。此外,该指南还减少了人们滥用异常作为美化返回值的诱惑,这是您永远不应该做的事情。

      【讨论】:

        猜你喜欢
        • 2010-09-13
        • 1970-01-01
        • 1970-01-01
        • 2015-11-25
        • 1970-01-01
        • 2019-04-28
        • 2014-12-22
        • 1970-01-01
        • 2019-04-05
        相关资源
        最近更新 更多