简体   繁体   English

C ++ catch构造函数异常

[英]C++ catch constructor exception

I do not seem to understand how to catch constructor exception. 我似乎不明白如何捕获构造函数异常。 Here is relevant code: 这是相关代码:

     struct Thread {
            rysq::cuda::Fock fock_;
            template<class iterator>
            Thread(const rysq::cuda::Centers &centers,
                   const iterator (&blocks)[4])
                : fock_()
            {
                if (!fock_) throw;
           }
      };

      Thread *ct;
      try { ct = new Thread(centers_, blocks); }
      catch(...) { return false; } // catch never happens,

So catch statement do not execute and I get unhandled exception. 所以catch语句不执行,我得到未处理的异常。 What did I do wrong? 我做错了什么? this is straight C++ using g++. 这是使用g ++的直接C ++。

You have to throw an object, eg, 你必须扔一个物体,例如,

throw std::exception();

throw with no operand is only used inside of a catch block to rethrow the exception being handled by the catch block. throw无操作数仅用于一个内部catch块重新抛出由正在处理的异常catch块。

You have to throw something in order to catch anything. 为了抓住任何东西,你必须抛出一些东西。

Try changing the line 尝试更改线路

if (!fock_) throw;

to

if (!fock_) throw "";

and observe the difference. 并观察差异。

You need to throw something. 你需要抛出一些东西。 throw alone means to "re-throw" the current exception. 单独throw意味着“重新抛出”当前的异常。 If there is no current exception, unexpected gets called, which will probably abort your program. 如果没有当前异常,则调用unexpected ,这可能会中止您的程序。

It's best to pick a class from <stdexcept> that describes the problem. 最好从<stdexcept>中选择一个描述问题的类。 logic_error or a derivative to indicate programming mistakes, or runtime_error to denote exceptional conditions. logic_error或指示编程错误的派生词,或指示异常情况的runtime_error

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM