Try/catch all block in C++ program not working - c++

Try/catch block in C++ not being "caught."
I'm trying to have one catch block to get all exceptions.
#include <iostream>
#include <exception>
using namespace std;
int main()
{
try
{
throw 1;
}
catch (exception& e)
{
cout << "ERROR: " << e.what() << endl;
return 1;
}
return 0;
}

throw 1; will throw an int. As you do not catch an int, the exception goes uncaught, which is undefined behavior. Though it is possible to throw anything, always prefer to throw a class that derives from std::exception. You can catch an int with catch(int e) or catch(...), but there's really no reason to ever do that.
If you catch with catch(...), then you do not know the type of the object, so cannot access any members, properties, or other aspects, and so you cannot* gather any information about what was thrown. This should never be used.
*There are ways to get information about the thrown object, but it's far easier to just catch the right type in the first place

You are throwing an int, but only catching std::exception. Use a catch(...) to catch everything thrown.

Related

Difference between catch(exception &e) and "catch(...)? [duplicate]

I know the difference in handling of both of these catches, but what does it take for the ellipse to catch something the std::exception catch wouldn't catch?
For example:
try
{
throw std::runtime("runtime error!");
}
catch(const std::exception& e)
{
std::cout << "Exception: " << e;
}
catch(...)
{
std::cout << "How did I get here?";
throw;
}
I've seen examples of code that use both of these in conjunction, but I've not seen a reason you would do both.
catch(const std::exception& e)
Will catch std exceptions only.
catch(...)
Will catch everything there after.
You can handle integers and other types (http://www.cplusplus.com/doc/tutorial/exceptions/)
For example:
catch(int e)
While it's definitely a good idea to do so, you don't have to derive your custom exceptions from std::exception. C++ allows you to throw practically any object type.
So throw 1; will not be handled by your first handler, for example. And neither will...
class MyCustomException { // Doesn't derive
///
};
... if it was thrown.
You probably meant:
throw std::runtime_error("runtime error!"); // not std::runtime
The std::runtime_error is derived from the std::exception so your first catch block is fired up as it catches exceptions of type std::exception. And there you probably meant:
std::cout << "Exception: " << e.what(); // not e
If you threw anything else other than the std::run_time or std::exception and its derivatives, the second catch block would be triggered. Useful reading from the C++ FAQ:
What should I throw?
As written, the throw statement throws an object whose type is derived from std::exception, so it's caught by the first catch clause. If you change the throw to throw 3; the exception will be caught by the second catch clause, not the first.

C++ - Do not understand the syntax of the catch function in try-catch

I've been learning about the try-catch block in C++ and I don't understand the syntax of the catch function. On cppreference, it says the following:
1) To declare a formal parameter in the catch clause:
catch (const std::exception& e) { /* */ }
2) To declare an unnamed parameter:
catch (const std::exception&) { /* */ }
3) To write a "catch-all handler" (not sure what this means), which is activated for any exception:
catch (...) { /* */ }
Questions:
1) What is the difference between these catch blocks? I'm not sure how a formal parameter, unnamed parameter, and a "catch-all handler" differ.
2) What type is the parameter e of the catch clause? Is it of type exception? I've never seen this type used other than in examples on how to write a try-catch block. If so, how could I use it in a catch clause to, let's say, output an error message? Can e accept a string I've sent in when I throw an error?
3) I've experimented and written a try-catch block as follows:
#include <iostream>
#include <string>
#include <stdexcept>
try
{
throw invalid_argument("Error, program stopped.");
}
catch(const string& e)
{
cout << e;
}
This code successfully calls the catch block and prints my message: "Error, program stopped.". However, the .exe suddenly stops working and crashes. I don't know if this is normal when an exception is thrown, or if my code is bad.
catch (const std::exception& e) { /* */ }
You need to use a named exception if you want to be able to access the exception object in the catch block. For example if you wanted to print e.what().
catch (const std::exception&) { /* */ }
You can use an un-named exception if you don't need to access the exception object. Maybe you don't care about the contents of the exception, and you just want to handle all exceptions (of this type) in the same way.
catch (...) { /* */ }
C++ allows you to throw an object of any type, whether or not it is of a type derived from std::exception. This type of catch block will catch anything thrown. Just like the un-named exception, you will not have access to the thrown object. But also, you won't even have any way to know what type it is.
For your final example, I don't think it is your catch block that is printing the message. After all, you're catching the wrong type. Some compilers will automatically insert exception catching code that will catch anything that escapes main, and if it is a type derived from std::exception, it will print the result of what(), before terminating the program. I believe GCC does this, but Visual Studio does not. Not sure about Clang or any other compilers.

Is it important that what() does not throw (exception classes)?

An exercise from C++ Primer asks
Why is it important that the what function [of exception classes] doesn’t throw?
Since there is no way to check my answer I was hoping to get an opinion. I thought possibly that it is an error (maybe terminate would've been called) to throw another exception during a catch clause (other than a rethrow throw;) while the current exception object is still being handled. It seems that is not the case though and it is completely okay to throw out of catch clauses:
#include <iostream>
using namespace std;
int main(){
try{
try{
throw exception();
} catch(exception err){ throw exception();}
} catch(exception err){ cout << "caught"} //compiles and runs fine, outputs "caught"
}
So program terminations are not a worry. It seems then, any problem that arises from what() throwing should, at the very least, be rectifiable by the user if they were so inclined.
Maybe then, the importance might be that while handling an error we do not want further unexpected errors to occur? Throws inside catch clauses are mainly intended for sending the exception object further up the call chain. A user may receive an error from deep in his program and does not want to worry that the error caught has to be associated with its own try block. Or maybe what() having its own throw may also lead to recursive effects (e.g. what() throws an exception, then we catch this exception and call what() but this then throws, and so on) meaning it might become impossible to handle any errors? How drastic can it be for what() to potentially throw?
I think there's nothing unclear - it's just as you described. If .what() method of an exception class throws an error, the whole catch effort was wasted:
try {
someDangerousOperation();
}
catch(std::exception e) {
// Ooops, instead of false,
//we get another exception totally unrelated to original error
someLogClassOrWhatever.save(e.what());
return false;
}
return true;
And Imagine the crazy code if you were expected to deal with what()'s exceptions:
try {
someDangerousOperation();
}
catch(std::exception e) {
// Not very fun
try {
someLogClassOrWhatever.save(e.what());
}
catch(...) {
alsoWhatHasFailedThatIsReallyGreat();
}
return false;
}
I think there's nothing more in that, probably the question is so simple it seems there must be some catch hiding in it. I think it's not the case.
std::exception::what() is noexcept. Consequently, if it throws, std::terminate is called. Yes, this is important.
Image a very curious coder with a slight tendency towards being a control freak (I know a couple of them myself), he really wants to know what is going wrong in his program and logs all errors with ex.what(). So he codes
try {
code();
}
catch(std::exception &e) {
std::cout<<e.what()
}
He is pretty pleased with the world in general and with himself in particular. But now it crosses his mind, that e.what() could throw an exception as well. So he is codes:
try{
try {
code();
}
catch(std::exception &e) {
std::cout<<e.what()
}
}
catch(std::exception &e) {
std::cout<<e.what()
}
A minute later he notices, that there is again an uncaught exception possible! Remember, he is a control freak, so he is going to write another try-catch block and than another and another
So you can bet any money, his project will be late - how could you do something like this to my friend? So please make sure e.what() doesn't throw:)
I guess it is the reason behind what being noexcept.

Why C++ biased towards destructor's exception?

#include <iostream>
using namespace std;
class Cls
{
public:
~Cls()
{
throw "exp";
}
};
int main()
{
try
{
Cls c;
throw "exp";
}
catch (...)
{
cout << "Why this doesn't call" << endl;
}
}
When I execute this code, it doesn't goes in catch block. And give following exception,
But, when I run this code with little modification, it goes to catch block.
int main()
{
try
{
throw "exp";
throw "exp";
}
catch (...)
{
cout << "Why this doesn't call" << endl;
}
}
Output:
Both the above code throws 2 exception, then why Compiler is biased in destructor's case?
In the first case you first throw from the try block and then the stack unwinding throws from Cls's destructor. So you have two exceptions to be handled. C++ handles this situation by calling terminate.
Because of the peculiarity of throwing from destructors, C++11 defines that all destructors are noexcept by default. Then even if there is no other exception to be handled, the exception from a destructor will cause terminate to be called.
The second case is OK because as soon as you throw the first exception try block is left and the exception is handled in the catch block.

a small issue in using exception handling in c++

The below given simple exception program is giving Unhandled Exception "Microsoft C++ exception: int at memory location 0x0012fe94..". I am getting this error immediately after the function excep() is returned.
Please can anyone tell why this error is coming here. Also it will be helpful if all the possible mistakes in this code were explained/analysed. I am learning to code better.
I am using Visual C++ 2005.
#include <iostream>
using namespace std;
int main ()
{
int excep(int);
throw excep(20);
return 0;
}
int excep(int e)
{
cout << "An exception occurred. Exception Nr. " << e << endl;
return 0;
}
If you try to learn exception throwing/handling your code contains an error.
function excep must handle object that was thrown not to be thrown itself.
your code must be rewritten as follows:
using namespace std;
int excep(int e)
{
cout << "An exception occurred. Exception Nr. " << e << endl;
return 0;
}
int main ()
{
int excep(int);
try
{ // <--------- Begin of try block. required part of the exception handling
throw 20;
}
catch (const int &errCode) // <------- we are catching only ints
{
excep(errCode); // Function that handles exception
}
return 0;
}
It is good design not to throw int variables, but type that inherites std::exception. But this is more advanced exception using knowledge
What did you expect to happen?
You call a function which prints out "An exception occurred", plus the other text, and then you throw the resulting value as an exception, which you never catch, so the program reports than an uncaught exception was thrown. Which is true, because that's exactly what you just did.
The entire point in exceptions is that when you throw an exception, it will propagate out through the program, until it is either handled, or it reaches the top level and terminates the program. You don't handle the exception, so it terminates the program.
If you want to handle an exception, you need to wrap the throwing code in a try block, followed by a catch, as in:
try {
throw excep(20);
}
catch (int ex) {
// do something about the exception
}
In the line
throw excep(20);
excep(20) is called first, whose return value is then thrown, i.e. you throw an integer. It is roughly equivalent to:
const int i = excep(20);
throw i;
To get you an idea how exception-snytax looks:
#include <iostream>
#include <stdexcept>
using namespace std;
int main ()
{
try {
// do something
throw std::runtime_error("test");
} catch (const std::exception &e) {
std::cout << "exception: " << e.what() << std::endl;
}
}
In practive: NEVER throw anything that is not derived from std::exception.
Proposed Readings:
Introductory book on C++ (search stackoverflow for this)
C++ FAQ on Exception Handling
"Exceptional C++" (for advanced C++ users)