这个C ++代码中catch的用法是什么

时间:2017-03-17 04:27:49

标签: c++ operators try-catch

您好我是C++编程的新手,我很难理解他们使用catch的代码。所以我想知道他们为什么在这段代码中使用catch。提前致谢

 #include <iostream>
 #include <exception>
 using namespace std;
 int main () 
 {
 try
 {
  int* myarray = new int[1000];
  cout << "allocated";
 }
 catch (exception& e)
 {
    cout << "Standard exception: " << e.what() << endl;
   }
    return 0;
  }

3 个答案:

答案 0 :(得分:5)

如果操作符new无法分配所需的空间,则它可能会抛出异常。

从上面的链接:

throwing (1)    void* operator new (std::size_t size) throw (std::bad_alloc);
  

如果无法分配存储空间,则抛出bad_alloc。否则,它会抛出   没有例外(无投保证)。

答案 1 :(得分:0)

catch块中的一个语句抛出异常时,try中的语句将被执行。本教程链接有助于实现:http://www.cplusplus.com/doc/tutorial/exceptions/

答案 2 :(得分:0)

尝试捕获C ++中的异常处理

  try
{

 int* myarray = new int[1000];

    cout << "allocated";
}

catch (exception& e)
{

cout << "Standard exception: " << e.what() << endl;

}

在这种情况下,首先它将使用try块检查内存分配,如果它无法分配内存然后使用catch它会抛出异常,那个内存无法分配