代码之家  ›  专栏  ›  技术社区  ›  Kelvin Shadewing

像这样的try语句有效吗?

  •  -3
  • Kelvin Shadewing  · 技术社区  · 10 年前

    我可以在我的主函数中只放一条涵盖整个程序的try-catch语句吗?还是所有功能都需要自己的?我的意思是,像这样的东西会起作用吗

    int main(){
        try{
            foo();
            bar();
        };
    
        catch(char* e){
            //Do stuff with e
        };
    };
    
    void foo(){throw "You'll never reach the bar.";};
    void bar(){throw "Told you so.";};
    

    如果没有,有没有类似的方法可以做到这一点?

    2 回复  |  直到 10 年前
        1
  •  2
  •   MikeCAT    10 年前

    你的例子行不通,因为

    • 声明 foo() bar() 在使用它们之前没有。
    • 后面的块之间有一个额外的分号 try catch .
    • 传递给什么 throw const char* ,但你只接住了 char* .

    这个例子奏效了。

    #include <iostream>
    
    void foo();
    void bar();
    
    int main(){
        try{
            foo();
            bar();
        }
    
        catch(const char* e){
            //Do stuff with e
            std::cout << e << std::endl;
        }
    }
    
    void foo(){throw "You'll never reach the bar.";}
    void bar(){throw "Told you so.";}
    
        2
  •  1
  •   Christian Hackl    10 年前

    我可以在我的主体中只放一个包罗万象的try-catch语句吗 覆盖整个程序的函数?

    catch (...) 捕捉一切。

    #include <iostream>
    
    int main()
    {
        try
        {
            // do something
        }
        catch (...)
        {
            std::cerr << "exception caught\n";
        }
    }
    

    还是所有功能都需要自己的?

    不,这将挫败例外的全部目的。

    catch(char* e){
        //Do stuff with e
    };
    

    此代码是由于误解异常是错误消息的结果。 异常不是错误消息。 C++中的异常可以是任何类型的。这包括 char* 当然,但这是完全不现实的。

    你真正想做的是抓住 std::exception 哪一个 包括 错误消息,可通过 what() 成员函数。编写良好的C++代码只抛出类型为 标准::异常 或派生类。您可以添加 ... 作为所有其他情况的备用:

     #include <iostream>
     #include <exception>
    
    int main()
    {
        try
        {
            // do something
        }
        catch (std::exception const& exc)
        {
            std::cerr << exc.what() << "\n";
        }
        catch (...)
        {
            std::cerr << "unknown exception caught\n";
        }
    }
    
    throw "You'll never reach the bar.";
    

    因此,抛出char数组是错误的。如果你期望 char const[] 要转换为 焦炭* ,但在设计层面上尤其错误。用专用异常类型替换数组,如 std::runtime_error :

    throw std::runtime_error("You'll never reach the bar.");
    
    推荐文章