c++ - 错误 : expected primary-expression before ';' token

标签 c++ exception

我得到了错误

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 

最佳答案

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

throw MyException();

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

关于c++ - 错误 : expected primary-expression before ';' token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17999422/

相关文章:

c++ - 我怎么能在 VC 2008 中删除 "error C4335: Mac file format detected"

c++ - 使用 std::equal_range 在某些范围内搜索 vector

java - 安卓/Java : UncaughtExceptionHandler and Bugsnag in parallel?

exception - mybatis异常时如何获取参数

java - 为什么我无法检查字符串中字符的成员资格?

c++ - 如何在 C++ 中创建文件映射?

c++ - Lambda 按值捕获和 "mutable"关键字

c++ - 如何在 3D 中绕 Z 轴旋转

php - 如何捕获 require_once/include_once 异常?

java - 如何在 JavaFX 线程之外更新 TableView 项目