How to construct a or exception without throwing?

前端 未结 4 941
自闭症患者
自闭症患者 2020-12-19 09:40

Exceptions defined in (e.g. std::logic_error, std::runtime_error and their subclasses such as std::system_erro

4条回答
  •  無奈伤痛
    2020-12-19 10:17

    if (haveError)
        throw std::runtime_error("BOO!"); // May throw std::bad_alloc instead?!
    

    by the time you reach this throw you should have already taken care of all clean up so in most cases, having a std::bad_alloc thrown instead of a std::runtime_error won't make much of a difference really.

    The only exceptional case, I can thing of is when exceptions are used to control the flow of a program - I tend to do this very often with code such as:

    try { 
      auto face = detectFace(); // may throw a custom no_face_exception or a many_faces_exception
      // do work with face
    } 
    catch (no_face_exception& e) {
      std::cout << "no face detected\n";
    }
    catch (many_faces_exception& e) {
      std::cout << "too many faces detected\n";
    }
    

    In this particular case failure to allocate memory would cause detectFace to throw a std::bad_alloc instead which would cause a disastrous crash. First allocating the exceptions before throwing, as you suggested, would not change anything at all - the program would still crash with a std::bad_alloc since the allocation would still fail. The only way around this problem would be to simply catch the std::bad_alloc:

    catch (std::bad_alloc& e) {
      std::cout << "bad alloc reported\n";
    }
    

提交回复
热议问题