2

我得到错误

error: expected primary-expression before ';' token

当我尝试编译以下代码时。问题是什么?

#include <iostream>
#include <stdexcept>
#include <exception>
using namespace std;

class MyException : public std::invalid_argument{};

int main() {
    try {
        throw MyException; //here is the problem
    }
    catch (...){
    }

    return 0;
}

我也试过这段代码

#include <iostream>
#include <stdexcept>
#include <exception>
using namespace std;

class MyException : public std::invalid_argument{};

int main() {
    try {
        throw MyException(); //here is the problem
    }
    catch (...){
    }

    return 0;
}

但后来我得到另一个错误

main.cpp: In constructor ‘MyException::MyException()’:
main.cpp:6:7: error: no matching function for call to ‘std::invalid_argument::invalid_argument()’
main.cpp:6:7: note: candidates are:
In file included from main.cpp:2:0:
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/stdexcept:86:14: note: std::invalid_argument::invalid_argument(const string&)
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/stdexcept:86:14: note:   candidate expects 1 argument, 0 provided
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/stdexcept:83:9: note: std::invalid_argument::invalid_argument(const std::invalid_argument&)
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/stdexcept:83:9: note:   candidate expects 1 argument, 0 provided
main.cpp: In function ‘int main()’:
main.cpp:10:27: note: synthesized method ‘MyException::MyException()’ first required here 
4

5 回答 5

7

您需要创建一个实际的对象来抛出:

throw MyException();

没有括号MyException只是类型,它不会创建对象。

于 2013-08-01T16:23:24.600 回答
6

有几个问题;

  • 基类std::invalid_argument没有默认构造函数,您需要向它传递一个字符串。
  • 您需要将参数传递给您的异常构造函数,或者至少调用()

换句话说,像这样;

class MyException : public std::invalid_argument {
public:
   MyException(const std::string& message) : std::invalid_argument(message) {}
};

int main() {
    try {
        throw MyException("bop"); //here is the problem
    }
...
于 2013-08-01T16:27:23.920 回答
6

MyException是一个类的名称,而不是一个对象。您必须在抛出期间创建类的新实例,如下所示:

throw MyException();

或抛出先前定义的类版本,如下所示:

myException except;
throw except;

请注意,在此示例中,第二个选项会很愚蠢,因为它会创建一个没有意义的临时变量,但在更复杂的情况下可能会很有用(也就是说,如果您在MyException类中有值和/或方法)。

于 2013-08-01T16:24:23.903 回答
0

试着把这样的东西:

    try{
        MyException excption;
        excption = /*...*/;
        throw excption;
        delete excption; //optional to delete excption once done with it
    catch(/*...*/)
    {
    //...
    }
于 2013-08-01T16:26:02.723 回答
0

这是你的主要方法

int main() 
{  
   try {  
          throw MyException; //here is the problem  
   }  
   catch (...){      
   }  
   return 0;  
}    

解决方案:

int main() 
{  
   try {
          MyException e;
          throw e; //problem solved    
   }  
   catch (...){      
   }  
   return 0;  
}  

说明:您看到 MyException 是一个类。您可以抛出该类的对象。

于 2013-08-01T16:41:58.937 回答