在这个C++代码中捕获的用法是什么
What is the usage of catch in this C++ code
嗨,我对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 它将抛出异常,无法分配内存
相关文章:
- 访问提升:shared_ptr 主范围外崩溃,断言失败:px != 0.指针的正确用法是什么?
- 使用 MSVC 编译时,msdpb* 文件的正确用法是什么?
- 引用和指向常量的指针的用法是什么
- 在这个C++代码中捕获的用法是什么
- constexpr 标准函子的正确用法是什么?
- ./lib/gcc/x86_64-linux-gnu/4.6/libstdc++.a 的用法是什么
- std::forward 在参数传递中的用法是什么?
- Boost:创建一组线程并等待所有线程的正确习惯用法是什么
- while(1)的用法是什么
- 逆方差的常见编程用法是什么?
- catch站点中异常的常见用法是什么
- ()运算符的这种特殊用法是什么意思
- 逗号运算符的正确用法是什么
- "!!"(否定两次)的用法是什么?
- CMake "project"指令的正确用法是什么
- “(无效)D”的用法是什么
- 在 C 语言中 &(AND) 运算符的用法是什么?
- 函数体中变量强制转换为 void 的这种用法是什么?
- std::unique_ptr 在推送到 std::vector 时的正确用法是什么?
- 取代snprintf(3)的c++习惯用法是什么?