【问题标题】:What does throw do when not in used with try and catch?throw 不与 try 和 catch 一起使用时有什么作用?
【发布时间】:2013-08-10 19:10:09
【问题描述】:

throw 不与 try 和 catch 一起使用时会做什么?喜欢:

 if (IsEmpty()) throw "Stack is empty, Cannot delete";

它会打印在控制台中吗?

但是当 throw 包含一些 int 或 char 作为其参数时,它会被抛出去捕获;在这种情况下会发生什么?

【问题讨论】:

  • 它使你的程序崩溃:-)
  • 与未捕获的 std::exception & 相同。
  • any 未捕获的异常相同; main() 之外的默认处理程序肯定会终止您的进程。

标签: c++ exception-handling try-catch throw


【解决方案1】:

C++ 运行时会有一些类似的东西(这不是它的样子,但你可以认为它是这样工作的,除非你正在处理一些非常特别的东西):

void BeforeMain()
{
     try
     {
        int res = main();
        exit(res);
     } 
     catch(...)
     {
         cout << "Unhandled exception. Terminating..." << endl;
         terminate();
     }
}   

【讨论】:

    【解决方案2】:

    您可以这样做,如果您没有放置显式的 try catch 块,它将不会在您的代码中的任何地方被捕获。 Windows 使用 SEH 机制来处理,你可以有一个未捕获的异常过滤器来解决这个问题

    查看这篇文章了解更多详情 Catching exceptions thrown without try/catch

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-07
      • 2010-12-14
      • 1970-01-01
      • 1970-01-01
      • 2015-02-01
      • 2022-01-21
      • 1970-01-01
      相关资源
      最近更新 更多