This simple example works as expected in g++, but in MS VS 2010 or 2013 shows a runtime library debug error (Invalid allocation size) before the error is caught (clicking Ignore does then flow through the error handler showing it correctly to be a bad_alloc).
Any ideas about why VS behaves this way?
#include <iostream>
#include <exception>
using namespace std;
int main() {
int x;
cout << "Enter -1 for bad_alloc: ";
cin >> x;
try
{
int* myarray = new int[x];
}
catch (exception& e)
{
cout << "Standard exception: " << e.what() << endl;
}
return 0;
}
That's so that you can analyse the exception at the point it is thrown, before the stack is unwound.
It's a feature that the debugger does this for you.
Nothing to worry about here.
Related
I am learning about the null_memory_resource and tried using it in a simple example. I set it as the default memory resource with set_default_resource and attempted to initialize a std::vector, but received a std::bad_alloc exception because the vector was trying to allocate memory using the null_memory_resource, which does not actually allocate any memory but throws an exception.
Now I am experimenting with a std::string and found that if the string size is below 16, no exception is thrown, but if the size is above 16, an exception is thrown. Any specific reason for this behavior?
The code snippet:
#include <iostream>
#include <memory_resource>
#include <string>
#include <vector>
#include <unistd.h>
int main()
{
std::pmr::memory_resource* default_resource = std::pmr::null_memory_resource();
std::pmr::set_default_resource(default_resource);
try
{
std::pmr::vector<std::uint8_t> data{1};
}catch(std::bad_alloc e)
{
std::cerr << "bad_alloc is thrown vector" << std::endl;
}
// No exception here if the size is below 16
std::pmr::string str1 {"abcdefghi"};
std::cerr << str1 << " Length:" << str1.size() << std::endl;
try
{
// Exception here if the size is >= 16
std::pmr::string str2 {"abcdefghijklmnop"};
}catch(std::bad_alloc e)
{
std::cerr << "bad_alloc is thrown string" << std::endl;
}
return 0;
}
Output:
bad_alloc is thrown vector
abcdefghi Length:9
bad_alloc is thrown string
online compiler:
https://godbolt.org/z/147ceMc7n
Edit1: Thanks for the info about SSO; now I understand the behavior of the program. But is there any way to avoid the SSO completely?
I have tried to create a program in C++ that can catch and handle bad_alloc exception.
While writing the code, I have noticed no errors but when I have tried to compile this code I got C2276 error code and C3876 in Microsoft Visual Studio Community 2017.
The error itself seems to appear in the catch{...} code block.
#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
class CanGoWrong {
public:
CanGoWrong() {
char *pMemory = new char[9999999999];
delete[] pMemory;
}
};
int main()
{
try {
CanGoWrong wrong;
}
catch(std::bad_alloc &e){
cout << "Caught exception: "<< e.what << e << endl;
}
cout << "Still running" << endl;
return 0;
}
The error with code C3867 ("non standart syntax, use &") I fixed this way :
from
cout << "Caught exception: "<< e.what << e << endl;
to:
cout << "Caught exception: "<< &e.what << e << endl;
Still, the error C2276 won't disappear. I guess there is something to do using basic std::exception class.
I want to understand how to do it right, this code is an course sample that I must follow and understand.
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;
}
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).
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/
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
I was writing a code for exception handling on Visual C++ 2010 .Here is the code
#include <iostream>
using namespace std;
// Localize a try/catch to a function.
void Xhandler(int test)
{
try{
if(test) throw test;
}
catch(int i) {
cout << "Caught Exception #: " << i << '\n';
}
}
int main()
{
cout << "Start\n";
Xhandler(1);
Xhandler(2);
Xhandler(0);
Xhandler(3);
cout << "End";
return 0;
}
The Program executed properly and the output was the as expected.But when I pressed the close button for closing the console then an error came that cmd has stopped working
.Then I ran my previous code that executed properly ,they also gave the same error
.
Can anybody tell why it is happening?Is it a problem with the Visual c++ 2010 or the code
I think your problem is not with your code. The problem is within your compiler tool chain. You probably are using Qt, and the tool chain has a problem causing this. Google the message you get when you crash with your IDE.
Here's a simple experiment to prove what I'm saying: just run this code:
int main()
{
cout << "Start\n";
cout << "End";
return 0;
}
And your program will crash, which means you have no problems with exceptions or anything else in your code, but with your tool chain.
Following is the code snippet I have written in the process of learning exception handling in C++(using visual studio 2010 compiler).
#include "stdafx.h"
#include <iostream>
using namespace std;
void multi_double() {
double first,second,product;
try{
cout << "Enter the first number\n";
cin >> first;
cout << "Enter the second number\n";
cin >> second;
product = first * second;
cout << product;
}
catch(...){cout << "Got an exceptional behaviour";}
}
void stud_age(){
int age;
try{
cout << "Enter student's age\n";
cin >> age;
if(age < 0)
throw;
cout << endl <<age;
}
catch(...) {
cout << "Caught here\n";
}
}
class Model{
public:
Model(){cout << "ctor\n";}
~Model(){cout << "dtor\n";}
};
int _tmain(int argc, _TCHAR* argv[]) {
//multi_double();
//stud_age();
int a;
try{
Model obj;
int *p = NULL;
*p = 0;//expecting access violation exception
}
catch(...){
cout << "caught an exception\n";
}
return 0;
}
Enable C++ exception is set to Yes[/EHsc].
But when I run the application,it is still crashing anyway ! with following information:
Problem signature:
Problem Event Name: APPCRASH
Application Name: DataTypeConversions.exe
Application Version: 0.0.0.0
Application Timestamp: 4ffd8c3d
Fault Module Name: DataTypeConversions.exe
Fault Module Version: 0.0.0.0
Fault Module Timestamp: 4ffd8c3d
Exception Code: c0000005
Exception Offset: 00001051
Why is not control coming to catch block?!
Access Violations and all other kinds of hardware exceptions are handled in Windows using a mechanism called "C Structured Exception Handling (SEH)". This was originally designed to give C programs a more "structured" way to handle exceptions than the usual signal()/sigaction() mechanism in Posix based systems.
SEH exceptions can be integrated into the C++ Exception system, by setting a translator function which is called before SEH stack unwinding takes place. The new translator function simply throws a C++ exception and, presto, C++ can catch the error!
See this Document from the MSDN for all the details:
http://msdn.microsoft.com/de-de/library/5z4bw5h5(v=vs.80).aspx
And here's a working example:
#include <windows.h>
#include <iostream>
#include <eh.h>
// You need to enable the /EHa excpetion model to make this work.
// Go to
// Project|Properties|C/C++|Code Generation|Enable C++ Exceptions
// and select "Yes with SEH Exceptions (/EHa)"
void trans_func( unsigned int u, EXCEPTION_POINTERS* pExp )
{
// printf( "In trans_func.\n" );
throw "Hardware exception encountered";
}
int main()
{
_set_se_translator(trans_func);
try
{
int *p = NULL;
*p = 0;//expecting access violation exception
}
catch(const char *s)
{
std::cout << "caught an exception:" << s << "\n";
}
return 0;
}
The C++ exception handling system can not hardware-generated (ie. access violation etc) exceptions, only exceptions generated by code through throw exception;.
If you want to catch these exceptions, it is only possible in Windows through the use of structured exceptions. This is not compatible with other compilers and uses the __try __except construct rather than normal try / catch.