Reputation:
Hi I am very new to C++
programming, and I am really hard to understand the code below in which they have used catch
. So I want to know why do they use catch
in this code. Thanks in advance
#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;
}
Upvotes: 1
Views: 106
Reputation: 153
try and catch come inside exception handling in C++
try
{
int* myarray = new int[1000];
cout << "allocated";
}
catch (exception& e)
{
cout << "Standard exception: " << e.what() << endl;
}
in this case first it wil check the memory allocation using try block and if it fail to allocate the memory then using catch it will throw exception,that memory could not be allocated
Upvotes: 0
Reputation: 1678
The statements in catch
will be executed when one of the statements in the try
block throws an exception. This tutorial link will helps a ton: http://www.cplusplus.com/doc/tutorial/exceptions/
Upvotes: 0
Reputation: 6875
The operator new
may throw an exception in case it cannot allocate the required space.
From the link above:
throwing (1) void* operator new (std::size_t size) throw (std::bad_alloc);
Throws bad_alloc if it fails to allocate storage. Otherwise, it throws no exceptions (no-throw guarantee).
Upvotes: 5