c++ No exception thrown while expecting out_of_range - c++

Consider the following source:
void ex8()
{
vector<int> v;
try
{
v.push_back(3);
int i = v[1];
}
catch (exception& e)
{
cout << "pas bon !";
}
}
When executing, no exception is thrown in Release. In Debug, I get a Debug Assertion Failed dialog.
I'am using Visual Studio on Win 10.
Is the vector implementation not supposed to throw an out_of_range exception?
Thank you.

Just an example with [] and at()
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v;
v.push_back(123);
v.resize(0);
try {
std::cout << "at() ";
std::cout << v.at(0) << std::endl;
}
catch (std::exception e) {
std::cout << e.what() << std::endl;
}
std::cout << "[] " << v[0] << std::endl; // all can append
return 0;
}
For me the execution is
at() std::exception
[] 123

Related

Why does this basic Try-Catch fail to catch [duplicate]

This question already has answers here:
Why doesn't 'd /= d' throw a division by zero exception when d == 0?
(5 answers)
Closed 1 year ago.
I am learning about try-catch constructs in C++ and I have the following example that appears to fail to execute the code inside either of the catches. I have spent the past few hours trying to find the bug/issue without luck.
I am wondering if there is an issue with g++ on my machine -- I am using mingw's g++ and Windows 10.
#include <iostream>
#include <stdexcept>
int main(){
try {
std::cout << "Start of Try-Catch\n";
int a = 13;
int b = 0;
int p = a/b;
std::cout << "printing p: " << p << std::endl;
p = 43;
std::cout << "Passed the div by zero issue\n";
} catch (std::runtime_error& e){
std::cout << "runtime error: " << e.what() << '\n';
return 2;
} catch (std::exception& e){
std::cout << "other error: " << e.what() << '\n';
return 3;
} catch (...) {
std::cout << "final catch\n";
return 4;
}
std::cout << "end of program\n";
return 0;
}
Instead, this is what happens when I compile and run:
C:\Users\...\Part 1>g++ cp_bug.cpp -std=c++17
C:\Users\...\Part 1>a.exe
Start of Try-Catch
C:\Users\...\Part 1>
it would be more logical to do something like that:
int main(){
try {
std::cout << "Start of Try-Catch\n";
int a = 13;
int b = 0;
if(b==0)
throw std::string("Passed the div by zero issue\n");
int p = a/b;
std::cout << "printing p: " << p << std::endl;
} catch (std::string e) {
std::cout << e;
return -1;
}
std::cout << "end of program\n";
return 0;
}
Your problem is that division by zero doesn't throw an exception that can be handled. Try the following tutorial instead.
Also this question is duplicated.

Run common code in case of any exception occurred in c++

I was looking similar to finally for c++ but I came across RAII. I have a small confusion though. If I have some common code I want to run in case of any exception,
Example: std::cout << "exception occured" << std::endl;
Is there a way to do that instead of copy the same code?
#include <iostream>
int main()
{
bool firstException = false;
try
{
if(firstException)
throw std::invalid_argument("the truth is out there!!");
else
throw std::domain_error("Bazzinga");
}
catch (std::invalid_argument const& e)
{
std::cout << e.what() << std::endl;
std::cout << "exception occured" << std::endl;
}
catch (std::domain_error const& e)
{
std::cout << e.what() << std::endl;
std::cout << "exception occured" << std::endl;
}
}
I got now what molbdnilo was talking about in the comment.
The code below has the answer. :) :D
#include <iostream>
int main()
{
bool firstException = true;
try
{
if(firstException)
throw std::invalid_argument("the truth is out there!!");
else
throw std::invalid_argument("Bazzinga");
}
catch (std::exception const& e)
{
std::cout << e.what() << std::endl;
std::cout << "exception occured" << std::endl;
}
}

How to issue a c++ termination catch without a OOM killer

I am learning about exceptions from a book and try/catch and the OS should terminate the following program.
The book says, the message terminate called after throwing an instance of 'std::bad_alloc' should show up. But doesn't.
I am using Arch Linux and the program is not stopping. It runs, fills the RAM a bit linear until it doesn't (at about 90%), the processor is working a lot but no freezing and no terminating.
Is this a Windows only use case or how could I reproduce the error on a Linux/maybe Unix system?
#include <iostream>
#include <exception> //c++ exception
int main()
{
int *feld;
int loop = 1;
for(;;) //infinite loop
{
std::cout << "Loop number: " << loop << '\n';
try
{
feld = new int[10000];
loop++;
if (durchlauf == 100000) //since c++11
std::terminate();
}
catch(...)
{
std::cout << "Error, Program done.\n";
break;
}
}
return 0;
}
EDIT: I found out that my OOM killer is not working properly with swap enabled/at all. But c++ has its own termination process call
https://en.cppreference.com/w/cpp/error/terminate
It just doesn't issues an exception to print out the catch line.
Has anyone a hint to issue a catch termination?
I found the following code for you to program some terminations:
Hope that helps.
#include <iostream>
#include <stdexcept>
struct A {
int n;
A(int n = 0): n(n) { std::cout << "A(" << n << ") constructed successfully\n"; }
~A() { std::cout << "A(" << n << ") destroyed\n"; }
};
int foo()
{
throw std::runtime_error("error");
}
struct B {
A a1, a2, a3;
B() try : a1(1), a2(foo()), a3(3) {
std::cout << "B constructed successfully\n";
} catch(...) {
std::cout << "B::B() exiting with exception\n";
}
~B() { std::cout << "B destroyed\n"; }
};
struct C : A, B {
C() try {
std::cout << "C::C() completed successfully\n";
} catch(...) {
std::cout << "C::C() exiting with exception\n";
}
~C() { std::cout << "C destroyed\n"; }
};
int main () try
{
// creates the A base subobject
// creates the a1 member of B
// fails to create the a2 member of B
// unwinding destroys the a1 member of B
// unwinding destroys the A base subobject
C c;
} catch (const std::exception& e) {
std::cout << "main() failed to create C with: " << e.what();
}
Just for the sake of being helpful if someone steps into the same problem
a coded thrown exception after 100000 loops:
#include <iostream>
#include <exception> //c++ exception
int main()
{
int *feld;
int loop = 1;
for(;;) //infinite loop
{
std::cout << "Loop number: " << loop << '\n';
try
{
feld = new int[10000];
loop++;
if (loop == 1e5)
throw std::bad_alloc(); //has to be inside the try(){} scope
}
catch(...)
{
std::cout << "Error, Program done.\n";
break;
}
}
return 0;
}

Catching overflows with boost::lexical_cast

I want to catch boost::lexicat_cast overflows the same way I can catch boost::numeric_cast overflows. Is it possible?
The first try block below throws a boost::numeric::negative_overflow.
The second block does not throw an exception (isn't this a lexical_cast bug?)
Though unsigned int is used in the example below, I am looking for a method that would work for any integer type.
#include <boost/numeric/conversion/cast.hpp>
#include <boost/lexical_cast.hpp>
int main()
{
unsigned int i;
try
{
int d =-23;
i = boost::numeric_cast<unsigned int>(d);
}
catch (const boost::numeric::bad_numeric_cast& e)
{
std::cout << e.what() << std::endl;
}
std::cout << i << std::endl; // 4294967273
try
{
char c[] = "-23";
i = boost::lexical_cast<unsigned int>(c);
}
catch (const boost::bad_lexical_cast& e)
{
std::cout << e.what() << std::endl;
}
std::cout << i << std::endl; // 4294967273
return 0;
}
You could write what you want using a modicum of Spirit:
Live On Coliru
#include <boost/spirit/include/qi.hpp>
#include <iostream>
template <typename Out, typename In> Out numeric_lexical_cast(In const& range) {
Out value;
{
using namespace boost::spirit::qi;
using std::begin;
using std::end;
if (!parse(begin(range), end(range), auto_ >> eoi, value)) {
struct bad_numeric_lexical_cast : std::domain_error {
bad_numeric_lexical_cast() : std::domain_error("bad_numeric_lexical_cast") {}
};
throw bad_numeric_lexical_cast();
}
}
return value;
}
int main()
{
for (std::string const& input : { "23", "-23" }) try {
std::cout << " == input: " << input << " -> ";
auto i = numeric_lexical_cast<unsigned int>(input);
std::cout << i << std::endl;
} catch (std::exception const& e) {
std::cout << e.what() << std::endl;
}
}
Prints
== input: 23 -> 23
== input: -23 -> bad_numeric_lexical_cast

Which vector threw index out of range exception?

I would like to access a reference to the std::vector which throws an out of range exception, or at least the line number where the exception was thrown (similar to Java's stack traces). Here is an example program:
#include <iostream>
#include <vector>
std::vector<int> vec1;
std::vector<int> vec2;
vec1.push_back(1);
vec2.push_back(2);
try
{
std::cout << vec1.at(1) << std::endl;
std::cout << vec2.at(1) << std::endl;
}
catch(Exception e)
{
// e.lineNumber()? e.creator_object()?
std::cout << "The following vector is out of range: " << ? << std::endl;
// or...
std::cout << "There was an error on the following line: " << ? << std::endl;
}
I know this example is trivial, but I hope it demonstrates what functionality I'm looking for.
EDIT: Implementation, from g++ --version: g++ (GCC) 4.1.2 20071124 (Red Hat 4.1.2-42)
You will need to do that yourself:
#include <iostream>
#include <vector>
std::vector<int> vec1;
std::vector<int> vec2;
vec1.push_back(1);
vec2.push_back(2);
try
{
std::cout << vec1.at(1) << std::endl;
}
catch(std::exception& e)
{
std::cout << "The following vector is out of range: " << "vec1" << std::endl;
}
try
{
std::cout << vec2.at(1) << std::endl;
}
catch(std::exception& ex)
{
std::cout << "The following vector is out of range: " << "vec2" << std::endl;
}