美文网首页
c++11 异常处理

c++11 异常处理

作者: googoler | 来源:发表于2020-04-21 10:13 被阅读0次

    引用来源

    概要

    异常是程序执行期产生问题,比如尝试除以零的操作。
    异常提供了一种转移程序控制权的方式。C++ 异常处理涉及到三个关键字:try、catch、throw:

    • throw: 当问题出现,程序通过throw抛出一个异常;
    • catch: 在你想要处理问题的地方,通过异常处理程序捕获异常;
    • try: try 块中的代码标识将被激活的特定异常。它后面允许跟着一个或多个 catch 块;
      使用 try/catch 语句的语法:
    try 
    {
         // 保护代码
    }
    
    catch( ExceptionName e1 ) 
    {
         // catch 块
    }
    
    catch( ExceptionName e2 )
     {
        // catch 块
    }
    
    catch( ExceptionName eN ) 
    {
        // catch 块
    }
    

    如果 try 块在不同场景抛出不同异常,此时可尝试罗列多个 catch 语句,用于捕获不同类型异常。


    抛出异常

    使用 throw 语句在代码块中任何位置抛出异常。throw 语句的操作数可以是任意表达式,表达式的结果类型决定了抛出异常的类型。

    示例:

    double division(int a, int b)
     {
    if( b == 0 )
     {
       throw "Division by zero condition!";
     } 
     return (a/b);
    }
    

    捕获异常

    catch 块跟在 try 块后面,用于捕获异常。可指定想要捕捉的异常类型,由 catch 关键字后括号内的异常声明类型决定。

    try {
    // 保护代码
     }
    
    catch( ExceptionName e ) {
    // 处理 ExceptionName 异常的代码
    }
    

    上面的代码会捕获一个类型为 ExceptionName 的异常。如果您想让 catch 块能够处理 try 块抛出的任何类型的异常,则必须在异常声明的括号内使用省略号 ...,如下所示:

    try {
     // 保护代码
     }
    catch(...) {
     // 能处理任何异常的代码
    }
    

    下面是一个实例,抛出一个除以零的异常,并在 catch 块中捕获该异常。
    实例

    #include <iostream>
    using namespace std;
    
    double division(int a, int b) {
     if( b == 0 ) {
      throw "Division by zero condition!";
     }
      return (a/b);
    }
    
    int main () {
        int x = 50; int y = 0; double z = 0;
        try {
            z = division(x, y); 
           cout << z << endl;
     }
    
     catch (const char* msg) {
      cerr << msg << endl;
     }  
    
     return 0;
    }
    

    此代码抛出了一个类型为 const char* 的异常,因此捕获异常时,须在 catch 块中使用 const char*。以上代码被编译和执行时,结果如下:
    Division by zero condition!


    C++ 标准异常

    C++ 提供一系列标准异常,定义在 <exception> 中,我们可以在程序中使用这些标准的异常。它们是以父子类层次结构组织起来的,如下所示:


    标准异常
    1. std::exception 该异常是所有标准 C++ 异常的父类。
    2. std::bad_alloc 该异常可以通过 new 抛出。
    3. std::bad_cast 该异常可以通过 dynamic_cast 抛出。
    4. std::bad_exception 这在处理 C++ 程序中无法预期的异常时非常有用。
    5. std::bad_typeid 该异常可以通过 typeid 抛出。
    6. std::logic_error 理论上可以通过读取代码来检测到的异常。
    7. std::domain_error 当使用了一个无效的数学域时,会抛出该异常。
    8. std::invalid_argument 当使用了无效的参数时,会抛出该异常。
    9. std::length_error 当创建了太长的 std::string 时,会抛出该异常。
    10. std::out_of_range 该异常可以通过方法抛出,例如 std::vector 和 std::bitset<>::operator
    11. std::runtime_error 理论上不可以通过读取代码来检测到的异常。
    12. std::overflow_error 当发生数学上溢时,会抛出该异常。
    13. std::range_error 当尝试存储超出范围的值时,会抛出该异常。
    14. std::underflow_error 当发生数学下溢时,会抛出该异常。

    自定义异常

    通过继承和重载 exception 类来定义新的异常。示例:

    #include <exception>
    
    using namespace std;
    
    struct MyException : public exception {
    
      const char * what () const throw () {
    
      return "C++ Exception";
    
     }
    
    };
    
    int main() {
    
    try { throw MyException(); }
    
    catch(MyException& e) {
    
     std::cout << "MyException caught" << std::endl; std::cout << e.what() << std::endl; }
    
     catch(std::exception& e) {
    
     //其他的错误 }
    
    }
    

    这将产生以下结果:

    MyException caught
    C++ Exception

    注解:

    1. what() 是异常类提供的一个公共方法,它已被所有子异常类重载。这将返回异常产生的原因。
    2. C++函数后面加关键字throw(something)限制,是对这个函数的异常安全性作出限制(注:c++11使用noexcept)。
      示例:
      void fun() throw() 表示fun不允许抛出任何异常,即fun是异常安全的。
      void fun() throw(...) 表示fun可以抛出任何形式的异常。
      void fun() throw(exceptionType) 表示fun只能抛出exceptionType类型的异常。

    c++11 noexcept关键字

    动态异常声明throw由于很少使用,在c++11中被弃用, 表示函数不会抛出异常的动态异常声明throw()也被新的noexcept异常声明取代, noexcept修饰的函数不会抛出异常, 在c++11中,如果noexcept修饰的函数抛出了异常,编译器可以选择直接调用std::terminate()来终止程序的运行,这比基于异常机制的throw()在效率上会高出一些。使用noexcept可有效阻止异常的传播与扩散:

    #include <iostream>
    using namespace std;
    
    void throw_(){ throw 1; }
    void NoBlockThrow(){ throw_(); }
    void BlockThrow() noexcept { throw_(); }
    
    int main()
    {
           /*try {
                  throw_();
           }
    
           catch (...){
                  cout << "found throw." << endl;
           }
           try   {
                  NoBlockThrow();
           }
    
           catch (...){
                  cout << "throw is not blocked" << endl;
           }*/
    
           try{
                  BlockThrow();
           }
    
           catch (...){
                  cout << "found throw 1" << endl;
           }
    
           //noexcept修饰的函数抛出异常,编译器直接调用std::terminate()终止程序运行
    }
    

    这个程序运行时,前两个try catch会正常输出xx到控制台,最后一个try-catch块,程序会弹出错误框表示程序已被终止,这是因为如果noexcept修饰的函数抛出了异常,那么编译器就直接调用std::terminate()终止了程序的运行。


    异常嵌套处理

    当处理第1个异常时,可能会触发第2种异常情况,从而要求抛出第2个异常,但问题是当抛出第2个异常时,正在处理的第1个异常信息会丢失。C++用嵌套异常(nested exception)的概念提供了解决这一问题的方案,嵌套异常允许将捕获的异常嵌套到新的异常环境。使用std::throw_nested()可以抛出嵌套了异常的异常。第2个异常的catch处理程序可以使用dynamic_cast访问代表第一个异常的nested_exception。

    下面的示例演示了嵌套异常的用法。
    示例定义了一个从exception派生的MyExcepion类,其构造函数接受一个字符串。

    #pragma once
    
    #include<exception>
    #include<iostream>
    #include<string>
    using namespace std;
    
    class MyException : public exception
    {
    public:
        MyException(const char* msg) :mMsg(msg) {}
        virtual ~MyException() noexcept {}
        virtual const char* what() const noexcept override {
            return mMsg.c_str();
        }
    private:
        string mMsg;
    };
    

    当处理第一个异常,且需要抛出嵌套了第一个异常的第二个异常时,需要使用std::throw_with_nested()函数。下面的doSomething()函数排除一个runtime_error异常,这个异常立即被处理程序捕获。捕获处理程序编写了一条消息,然后使用throw_with_nested()函数抛出第二个异常,第一个异常嵌套在其中。注意嵌套异常时自动实现的。

    void doSomething()
    {
             try {
                       throw runtime_error("Throwing a runtime_error exception");
             }
    
             catch (const runtime_error&e) {
                       cout << __func__ << " caught a runtime_error" << std::endl;
                       cout << __func__ << " throwing MyException" << endl;
                       throw_with_nested(MyException("MyException with nested runtime_error)"));
     }
    

    下面的main()函数演示如何处理嵌套异常。该段代码调用了doSomething()函数,还有一个处理MyException类型异常的处理程序,当捕获到这类异常时,会编写一条消息,然后使用dynamic_cast访问嵌套的异常。如果内部没有嵌套异常,结果为空指针。如果存在嵌套异常,调用nest_exception的rethrow_nested()方法。这样会再次抛出嵌套的异常,这一异常可以在另一个try/catch块中捕获。

    int main()
    {
             try {
                       doSomething();
             }
    
             catch (const MyException&e)
             {
                       cout << __func__ << " caught MyException: " << e.what() << endl;
                       const nested_exception *pNested = dynamic_cast<const nested_exception*>(&e);
    
                       if (pNested)      {
                                try     {
                                         pNested->rethrow_nested();
                                }
    
                                catch (const std::runtime_error& e)    {
                                         //handle nested exception
                                         cout << " Nested exception: " << e.what() << endl;
                                }
                       }
             }
             return 0;
    }
    

    输出结果:

    doSomething caught a runtime_error
    doSomthing throwing My Exception
    main caught MyException: MyException with nested runtime_error>
    Nested exception: Throwing a runtime_error exception

    相关文章

      网友评论

          本文标题:c++11 异常处理

          本文链接:https://www.haomeiwen.com/subject/napyihtx.html