googletesting out of range - c++

I have a vector<string> and a method(inside a class) that returns a character at a certain position.
This is all happening in try catch block.
The problem appears when I try to google test this method, purposely invoking the std::out_of_range exception with EXPECT_THROW(method, std::out_of_range), but instead of getting a passed test I get several .what() error messages vector::_M_range_check and a test failure.
mentioned method
char ClassA::getC(int x, int y){
try{
return vec.at(y).at(x);
catch(const out_of_range& e){
cout << '\n' << e.what() << '\n';
return 0;
}
}
There's also a similar void method that sets a different char at a certain position where I just call vec.at(y).at(x) = c; and where I'd also like to catch std::out_of_range
So what am i doing wrong?

EXPECT_THROW(method, std::out_of_range)
What you're saying here is that you expect the method to throw this exception. That's what is wrong.
That'll never happen because that exception is handled in the method.
The error messages come from cout << ....
On a more fundamental level, your tested function is wrong. That's not the way you want to handle exceptions in your application.

Related

When exactly has an exception been caught?

I get this terminating with uncaught exception even though I thought I had caught the exception. Here is some example code
#include <iostream>
#include <stdexcept>
void throwing(int x)
{
if(x) throw std::runtime_error("x non-null");
}
int main()
{
try {
throwing(1);
} catch(std::runtime_error const&ex) {
std::clog << "error: \"" << ex.what() << '\"' << std::endl;
std::terminate();
}
return 0;
}
which produces (after reporting error: "x non-null") the said message (using clang++ with std=c++11). So, when exactly has the exception been caught and hence deemed uncaught in the sense of terminate() not reporting it (again)? Or, equivalently (or not?): how can I catch an exception, report its what(), and terminate() without getting this blurb?
(I could refrain from reporting the what() and just terminate(), but I want to report the what() in my own way.)
Since noone provided an answer to this, and it seems like my comment was either not clear enough or overlooked, I'll post a full answer:
Or, equivalently (or not?): how can I catch an exception, report its what(), and terminate() without getting this blurb?
If you read carefully thru the reference, you'll notice std::terminate() by default calls abort(), which causes the program to terminate returning a platform-dependent unsuccessful termination error code to the host environment.
Now, answering the quoted question: either use exit(int status) (which is a better solution, since you handled the exception) instead of terminate, or change the terminate handler.

What does throw do when not in used with try and catch?

What does throw do when not used with try and catch? Like:
if (IsEmpty()) throw "Stack is empty, Cannot delete";
Does it get printed in console?
But when throw contains some int or char as its arguments, it is thrown to catch; what happens in this case?
The C++ runtime will have something along the lines of (this is NOT exactly how it looks, but you can think of it as working this way, unless you are working on something very special):
void BeforeMain()
{
try
{
int res = main();
exit(res);
}
catch(...)
{
cout << "Unhandled exception. Terminating..." << endl;
terminate();
}
}
You are allowed to do that, and it will not be caught anywhere within your code if you have not put an explicit try catch block.
Windows uses a SEH mechanism to handle , where you could have an uncaught exception filter to figure out about the same
See this post for more details
Catching exceptions thrown without try/catch

What could be overriding the return code from main()?

I have a rather odd occurrence happening that I haven't been able to nut out yet.
I have test case that is supposed to catch errors and return the appropriate error code from main, but /sometimes/ on test runs the program returns 0 even when the error code is non zero.
The exception class thrown is:
class exit_request {
public:
explicit exit_request(int code = 0) : m_code(code) {}
int code() const { return m_code; }
private:
int m_code;
};
The test case code is:
int main(int argc, char* argv[])
{
try {
// Do some test case stuff
// Eventually, due to the supplied command line arguments,
// we expect an exit_request() to be thrown from within
// library code.
}
catch (exit_request& exp) {
std::cout << "Exit Request:" << exp.code() << std::endl;
return exp.code();
}
catch (std::exception& err) {
std::cout << "Error: " << err.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
In many runs of this test case, everything works as expected: The exit_request() exception is thrown, caught, exp.code() is printed (its value is 2), and the return code from the process is 2.
However, very occasionally, the return code from the process is 0 (i.e. no failure), even though exp.code() is printed as 2.
Can anyone help explain a situation in which this can occur? i.e. the return value from main is changed from non-zero to zero before the process exits?
This is occurring on Windows 7 (x64), with MSVC++ 2010 Express, building a x86 (32-bit) application. I have not seen this odd failure on any of our other Windows or Linux platforms, or compilers, but that doesn't necessarily mean it couldn't happen in those environments.
If you have any atexit handlers that call exit(0), or any static-storage-duration objects whose destructors do that, it might explain what you're seeing. They get executed after your return statement. It's undefined behavior, which could explain why you only see it happen sometimes.
Maybe you are not throwing the exception correctly...
I mean that from the function called or processing done in try block, you are throwing exception of some other type.
Try to write a default catch block for that.

ellipsis try catch on c++

Can an ellipsis try-catch be used to catch all the errors that can lead to a crash? Are there are any anomalies?
try
{
//some operation
}
catch(...)
{
}
No, it'll only catch C++ exceptions, not things like a segfault, SIGINT etc.
You need to read up about and understand the difference between C++ exceptions and for want of a better word, "C-style" signals (such as SIGINT).
If the code inside try/catch block crashed somehow, the program is anyway in a non-recoverable state. You shouldn't try to prevent the crash, the best that the program can do is just let the process crash.
The "anomaly" is in the fact that your code only catches the exceptions, and not the errors. Even if the code is exception-safe (which may be not the case, if you are trying to work-around its mistakes by a try/catch block), any other inner error may bring the program into irrecoverable state. There is simply no way to protect the program from it.
Addition: look at this article at "The Old New Thing" for some insights.
It is the Catch All handler.
It catches all the C++ exceptions thrown from the try block. It does not catch segfault and other signals that cause your program to crash.
While using it, You need to place this handler at the end of all other specific catch handlers or it all your exceptions will end up being caught by this handler.
It is a bad idea to use catch all handler because it just masks your problems and hides the programs inability by catching all(even unrecognized) exceptions. If you face such a situation you better let the program crash, and create a crash dump you can analyze later and resolve the root of the problem.
It catches everything that is thrown, it is not limited to exceptions. It doesn't handle things like windows debug asserts, system signals, segfaults.
TEST(throw_int) {
try {
throw -1;
} catch (std::exception &e) {
std::cerr << "caught " << e.what() << std::endl;
} catch (...) {
std::cerr << "caught ..." << std::endl;
}
}
Throwing an integer isn't really recommended though. It's better to throw something that inherits from std::exception.
You might expect to see something like this as a last ditch effort for documenting failure, though. Some applications aren't required to be very robust. Internal tools might cost more than they are worth if you went through the paces of making them better than hacked together crap.
int main(int argc, char ** argv) {
try {
// ...
} catch (std::exception &e) {
std::cerr << "error occured: " << e.what() << std::endl;
return 1;
}
return 0;
}

how to get message of catch-all exception [duplicate]

This question already has answers here:
C++ get description of an exception caught in catch(...) block
(6 answers)
Closed 6 years ago.
If I want to write useful info to a file whenever i caught a catch-all exception, how to do it?
try
{
//call dll from other company
}
catch(...)
{
//how to write info to file here???????
}
You can't get any information out of the ... catch block. That is why code usually handles exceptions like this:
try
{
// do stuff that may throw or fail
}
catch(const std::runtime_error& re)
{
// speciffic handling for runtime_error
std::cerr << "Runtime error: " << re.what() << std::endl;
}
catch(const std::exception& ex)
{
// speciffic handling for all exceptions extending std::exception, except
// std::runtime_error which is handled explicitly
std::cerr << "Error occurred: " << ex.what() << std::endl;
}
catch(...)
{
// catch any other errors (that we have no information about)
std::cerr << "Unknown failure occurred. Possible memory corruption" << std::endl;
}
A caught exception is accessible by the function std::current_exception(), which is defined in <exception>. This was introduced in C++11.
std::exception_ptr current_exception();
However, std::exception_ptr is an implementation-defined type, so you can't get to the details anyway. typeid(current_exception()).name() tells you exception_ptr, not the contained exception. So about the only thing you can do with it is std::rethrow_exception(). (This functions seems to be there to standardize catch-pass-and-rethrow across threads.)
There's no way to know anything about the specific exception in a catch-all handler. It's best if you can catch on a base class exception, such as std::exception, if at all possible.
You can't get any details. The whole point of catch(...) is to have such "I don't know what can happen, so catch whatever is thrown". You usually place catch(...) after catch'es for known exception types.
I think he wants to make it log that an error occurred, but doesn't specifically need the exact error (he would write his own error text in that case).
The link DumbCoder posted above has at tutorial that will help you get what you're trying to achieve.