相关疑难解决方法(0)

main()周围没有花括号 - 为什么这有效?

我正在编写一本关于C++的书和关于它有错误的章节(我留下了一些小问题,但主要是这个):

int main()
try { 
        // our program (<- this comment is literally from the book)
        return 0;
}
catch(exception& e) {
    cerr << "error: " << e.what() << '\n';
    return 1;
}
catch(...) {
    cerr << "Unknown exception\n";
    return 2;
}
Run Code Online (Sandbox Code Playgroud)

这编译但当然没有做任何事情,所以我仍然在想

  1. 为什么在main()之后没有一组花括号括起来?是块还是我称之为"流行语"(ha!)是main()的一部分还是没有?
  2. 如果它们是函数,那么在catch之前没有"int"(无论如何)?
  3. 如果它们不是功能,它们是什么?
  4. 重新捕捉(...),我从未见过用这种方式使用的椭圆.我可以在任何地方使用省略号来表示"任何东西"吗?

c++ syntax error-handling

27
推荐指数
3
解决办法
2106
查看次数

异常被捕获两次

class A{
    public:
        A() { throw string("exception A"); };
};

class B{
    A a;
    public:
        B() try : a() {} catch(string& s) { cout << &s << " " << s << endl; };
};

int main(){    
    try{
        B b;
    }catch(string& s){
        cout << &s << " " << s << endl;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

0x32c88 exception A
0x32c88 exception A
Run Code Online (Sandbox Code Playgroud)

由于异常已经在构造函数中被捕获B,为什么它仍然出现在main函数中?

c++ constructor exception

12
推荐指数
1
解决办法
616
查看次数

标签 统计

c++ ×2

constructor ×1

error-handling ×1

exception ×1

syntax ×1