c ++ - try块后是否需要立即写入catch块?

时间:2018-03-16 18:26:34

标签: c++ c++11 error-handling exception-handling try-catch

我的编译器给出了以下代码的错误:

#include <iostream>
#include <stdexcept>

using namespace std;


void test()
{
     throw runtime_error("Error");
}

int main()
{
     try
     {
          test();
     }

     for (int i = 0; i < 10; i++)
     {

     }

     catch (exception& e)
     {
          cout << e.what();
     }
}

它说&#34;错误:预期&#39; catch&#39;之前&#39;(&#39;令牌&#34;,它指的是&#39;(&#39;在for循环初始化。

我必须在try块之后立即编写catch块吗?我认为如果在try块中抛出一个错误,程序将冒出来,直到它找到一个合适的catch块。为什么不适用于此?

2 个答案:

答案 0 :(得分:7)

是的。是的,我的意思是。

要明确,因为有些人似乎对上述简短回答感到困惑:

一个捕获块确实需要在try块后立即写入。

还有一个次要问题:

  

我认为如果在try块中抛出错误,程序将冒出来,直到找到合适的catch块。为什么不适用于此?

因为你只能在try块之后立即写一个catch块。其他任何事情都是形成不良的计划。

答案 1 :(得分:0)

它应该总是类似于这个伪代码: reference

public void registerReceiver(Context act, IntentFilter filt, Looper looper)