Program doesn't stop after exception

后端 未结 6 807
悲哀的现实
悲哀的现实 2021-01-21 03:11

I am using eclipse in Ubuntu 12.04. I use some exceptions in my program and when they are caught it gives me cout correctly. But the program continues to the end. Is there a way

6条回答
  •  遥遥无期
    2021-01-21 04:04

    To stop execution of a program after catching an exception, just call std::exit() in the catch block:

    #include 
    #include 
    
    int main()
    try
    {
      throw 42;
    }
    catch(int i)
    {
      std::cout << "Caught int: " << i << ". Exiting...\n";
      std::exit(EXIT_FAILURE);
    }
    

    Live demo here.

    This works outside of main as well. You can substitute EXIT_FAILURE with any int value you want, portably in the 0-255 range.

提交回复
热议问题