在这个C++代码中捕获的用法是什么

What is the usage of catch in this C++ code

本文关键字:用法 是什么 C++ 代码      更新时间:2023-10-16

嗨,我对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;
  }

运算符new如果无法分配所需的空间,则可能会引发异常。

从上面的链接:

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

如果无法分配存储,则引发bad_alloc。否则,它会抛出 没有例外(无抛掷保证(。

try块中的一个语句引发异常时,将执行 catch 中的语句。本教程链接将帮助很多:http://www.cplusplus.com/doc/tutorial/exceptions/

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

  try
{
 int* myarray = new int[1000];
    cout << "allocated";
}
catch (exception& e)
{
cout << "Standard exception: " << e.what() << endl;
}

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