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

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

Related

Is it OK to create Gtk::Builder from resource without implementing try/catch block?

Gtk::Builder::create_from_resource() throws the following exceptions when something goes wrong, for instance, the resource file wasn't found or there's a markup error in the Glade/UI file, etc
BuilderError
Glib::MarkupError
Gio::ResourceError
But I don't have any intention to handle those exceptions and do something else in my GTKMM program.
In case, if I have to implement try/catch block out of good programming practice, bare basic code would look like this:
try {
auto resource = Gtk::Builder::create_from_resource("/domain/reverse/myappid");
} catch (const Gio::ResourceError &ex) {
cerr << ex.what();
} catch (const Glib::MarkupError &ex) {
cerr << ex.what();
} catch (const Gtk::BuilderError &ex) {
cerr << ex.what();
}
I'm just printing the same exception message if any one of them was thrown... But anyway even without implementing the try/catch block, I still get the same meaningful message. And in both cases, the program would run just fine, no application crashes intended. Just the info printed on console for developers.
So is it safe to write less and readable code without the try/catch block for Gtk::Builder::create_from_resource?
If you really don't want to handle the exception, the program will simply terminate abruptly if some exception is thrown.
I personally prefer to use global exception handling in these cases. In your case, all exceptions derive from std::exception or Gtk::BuilderError, so your handler could look like:
int main()
{
try
{
// Program code, eventually a call to `Gtk::Builder::create_from_resource`.
}
catch(const std::exception& p_exception)
{
cerr << p_exception.what();
}
catch(const Gtk::BuilderError& p_exception)
{
cerr << p_exception.what();
}
return 0;
}
What I like about this is that I don't have to put try-catch blocks everywhere for exceptions I have no intention of handling (ex.: the user somehow revoved the ressource file), but I can log something for debug purposes, or warn the user instead of simply crashing (i.e terminating).
You could also use the catch-all syntax:
int main()
{
try
{
// Program code, eventually a call to `Gtk::Builder::create_from_resource`.
}
catch(...)
{
// Do something, but the exception message is not available.
}
return 0;
}
This has the advantage of catching everything (even exceptions that are not child classes of std::exception), but has the disadvantage that you loose the exception message, as least for standard C++.

googletesting out of range

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.

How to catch exception without throw

There is a CRASH in Function() due to some exceptions so, throw X would not be called. In this case how to call catch block to handle exceptions?
NOTE: we can't modify the code in Function() definition
Sample code:
cout << "Before try \n";
try {
abc->Function(); //Here is CRASH
throw x;
cout << "After throw (Never executed) \n";
}
catch (...) {
cout << "Exception Caught \n";
}
cout << "After catch (Will be executed) \n";
So can anyone help me out for this?
A "CRASH" is not an exception. It is Undefined Behaviour. Absolutely anything could have happened. You are lucky that the system detected it. It could have formatted your disk or summoned daemons out of your nose. Instead the system is only shutting down the process to prevent further damage.
The system might even be so kind as to let you define what to do instead of shutting down the process. The way to define it is system specific. In Unix, you need to install signal handler (the advanced way), in Windows you use structural exceptions.
But the problem is that if the function crashed, there is no way to tell how big mess it left the memory of the process in. You really have to fix the crash. A crash is always a bug.
The fact that a crash is inside that function does not automatically mean the bug is in that function. Most crashes I've seen happened in standard library functions, but they were not bugs in standard library. They were caused by incorrect use of those functions, or sometimes incorrect use of something different much earlier in the program. Because when you invoke Undefined Behaviour, there's no telling when it will cause a crash. Especially buffer overruns and writes to uninitialized pointers tend to cause crashes eventually when some unrelated code wants to use the variable that was overwritten.
That said if the bug is indeed in that function and you can't modify it, you will have to get somebody who can or find an alternative that works better. Because there's no way the program is going to work correctly otherwise.
There's an aditional '}' in the try block in your code. Not sure whether that was an error in typing the code or from another higher level block.
The catch(...){} block will be executed when any unhandled exception is thrown inside the try {} block. It doesn't matter whether the exceptions are thrown directly under the block or somewhere deep down in other function calls in the block.
cout << "Before try \n";
try
{
abc->Function1(); //A potential for crash
abc->Function2(); //Another potential for crash
abc->Function3(); //Another potential for crash
// Do some checks and throw an exception.
throw x;
cout << "After throw (Never executed) \n";
}
catch (...)
{
// This will catch all unhandled exceptions
// within the try{} block. Those can be from
// abc->Function1(), abc->Function2(), abc->Function3(),
// or the throw x within the block itself.
cout << "Exception Caught \n";
}
cout << "After catch (Will be executed) \n";
Hope that is helpful.
Here us the meaning of try and catch
try {
//[if some ABC type exception occur inside this block,]
}catch (ABC) {
//[Then, Do the things inside this block.]
}
So
after the exception occur in your abc->Function(); flow will directly jump in to catch block so write there what you need to do. as example.
try {
abc->Function(); //Here is CRASH
throw x;
cout << "After throw (Never executed) \n";
}catch (Exception ex) {
cout << "Exception Caught \n";
throw ex;
}
actually throw x; doesn't have any use here. because if your abc->Function(); worked fine, then it will throw an exception. so just remove that line.
the code you have written works exactly true . the compiler when see the throw command every where in the try{} it will go to the catch(){} so the cout << "After throw (Never executed) \n"; won't execute and then the code after the catch(){} will execute
for reading more about this case here is the link trycatch
If you got exception ,
abc->Function(); //Here is CRASH
You will enter in catch(...) block.
If you are using Windows OS, for OS generated exceptions you also need to use __try/__catch

Exception mechanism issue in c++

I am calling a function and I am throwing an exception in that function. But I don't want to catch that in the same function but want to catch it where that function was called, like here is my example code.
void foo()throw(...){
std::cout << "FOO" <<std::endl;
throw "Found";
}
void main(){
try{
foo();
}
catch(...){
std::cout << "exception catched" <<std::endl;
}
}
But it is crashing at the point where I am throwing the exception in foo function, but I want to catch it in the main function.
How would I do that?
throw;
throw with no operand rethrows the exception that is currently being handled. That means it can only be used in a catch block. Since you aren't in a catch block when the throw; is executed, the program is terminated.
You need to throw something, like a runtime error: throw std::runtime_error("oops");.
Note also that exception specifications (e.g. the throw(...) in void foo() throw(...)) should not be used. For an explanation as to why, see "A Pragmatic Look at Exception Specifications."
Got answer my own question at http://msdn.microsoft.com/en-US/library/wfa0edys%28v=VS.80%29.aspx

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;
}