Function-body exceptions [duplicate] - c++

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Difference between try-catch syntax for function
What is the difference in the utility and behavior of these try-catch blocks? When would I prefer one form over the other?
int f() {
try {
...
} catch(...) {
...
}
}
int f() try {
...
} catch (...) {
...
}

If the entire body must go into the exception block, I tend to prefer the 2nd form as it's easier to read (e.g. one less indentation level).
However, the main place where this makes a difference is in constructors. Consider:
Foo::Foo ()
try : member_with_throwing_constructor(initial_value)
{
}
catch ( ... )
{
// will process exceptions thrown by `member_with_throwing_constructor`
// this will be added by the compiler if you
// don't finish by a `throw ...` statement.
throw;
}
and
Foo::Foo ()
: member_with_throwing_constructor(initial_value)
{
try
{
}
catch ( ... )
{
// does not catch exceptions thrown in constructor
// of `member_with_throwing_constructor`.
}
// can keep processing if `catch` handler does not `return` or `throw`.
}
These two code snippets have radically different behavior. The first one will catch exceptions raised in data member constructors (usually through the initializer list, but default constructors apply too) and will automatically re-raise the exception because the instance could not be created safely. The second form does not cover data member initialization and allows you to choose whether to keep the object or not.
I also like to add a global try-catch in main() to help with debugging uncaught exceptions. The following snippet:
int main ( int, char ** )
try
{
// main program...
}
catch ( const std::exception& error )
{
std::cerr << "Uncaught exception: '" << error << "'." << std::endl;
return (EXIT_FAILURE);
}
catch ( ... )
{
std::cerr << "Uncaught exception of unknown type." << std::endl;
return (EXIT_FAILURE);
}
Some people will argue that not catching the exceptions allows the program to crash and you can get a core dump to help with debugging. While this may be useful in debug mode, as it can help the debugger point you to the exact line of code that raised the exception, I like to ship programs that don't crash, and I can show the user a message saying a bug report was submitted.

Function try-catch blocks are only useful in constructors, and even then, not very useful at all. It's best to just forget they exist.

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++.

Try/catch whole program [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I've taken the habit to construct my C++ projects as follows :
int main(int ac, char* av[])
{
try
{
Object foo;
foo.run()
/* ... */
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
return 1;
}
catch (...)
{
std::cerr << "Unknown error." << std::endl;
return 1;
}
return 0;
}
I wonder if this is a good practice, or is it better to use try/catch blocks on small pieces of codes that are "expected" to produce errors ?
Generally, catching all exceptions is not a good idea: you want to catch only these exceptions that your particular piece of code is ready to handle in a meaningful way.
However, the top-level entry point is an exception from this rule: it is a common practice to catch all exceptions yourself if you wish to control how exceptions are processed on the top level.
A common way of implementing it, however, is to write a single function that looks like main, but has a different name:
int entryPoint(int argc, char *argv[]) {
... // The real logic goes here
Object foo;
foo.run()
/* ... */
}
Your code looks like this, and never changes:
int main(int ac, char* av[])
{
try
{
return entryPoint(ac, av);
}
catch (const std::exception& e)
{
std::cout << e.what() << std::cerr;
}
catch (...)
{
std::cout << "Unknown error." << std::endl;
}
}
You can put your whole program into such a top-level exception-handler, if you want to control how unhandled exceptions are handled (if they reach top-level).
There is a dis-advantage to that though: The standard crash-behavior is pre-empted, which probably means you get no crash-dumps, and thus are missing crucial information for post-mortem debugging.
Also, they might not reach top-level, but result in std::unexpected() and by that std::terminate() being called.
Thus, you might be better served by std::set_terminate even if you want to do your own thing.
Consider doing your own thing and then crashing like normal (Which you cannot do with your global exception-handler).
The advantage is your program never crashing (on Linux it can crash tough, since signals can't be caught as exceptions)
But there is one disadvantage I can think of: When you debug your code and have a run time error, you don't know where it was or see the stack. since your program continue running from the catch. so instead of check immediately what happened you need to run again and hope you'll have the same behavior.
Another thing: if your program is Multi-threaded, it won't help to caught all exceptions, since each thread need to catch his own exceptions.
It's certainly better to try/catch as near the throw as possible if you can do something to recover from the error. Catching every fatal error on the other hand may clutter your code quite a bit.
If a throw is not caught, std::terminate will be called and you can set that function to a custom one with std::set_terminate. Inside the terminate function, you can do throw; which rethrows the uncaught object and then catch it. You must use catch(...) at the end in this case, since throwing from the terminate function is not a good thing.
Yes surely it would make difference...Let's see how.
try
{
// code which could throw an exception
}
catch(Myexception& e) //derived from std::exception
{
//do something.
}
//..some more code. //Point_1
Let's say I just want to do some manipulation after catching Myexception then then resume this function. After catching the exception code would come to POINT_1. Had I encapsulated this in try/catch it would have been ignored.

C++ try / catch (new to programming and not much info about this clause)

I am new to programming and am having trouble with try / catch clauses.
Here is an example from a textbook that I have:
int main( )
{
char *ptr;
try {
ptr = new char[ 1000000000 ];
}
catch( … ) {
cout << "Too many elements" << endl;
}
return 0;
}
I have tried to look online for a further explanation and the textbook does not exactly tell me what what these clauses actually do or what it is used for.
Any information would be helpful.
EDIT: The textbook I am using is:
C++: Classes and Data Structures by Jeffrey Childs
A try-catch is the C++ construct for exception handling. Google 'C++ exceptions'.
Try catch is a way of handling exceptions:
try
{
// Do work in here
// If any exceptions are generated then the code in here is stopped.
// and a jump is made to the catch block.
// to see if the exception can be handled.
// An exception is generated when somebody uses throw.
// Either you or one of the functions you call.
// In your case new can throw std::bad_alloc
// Which is derived from std::runtime_error which is derived from std::exception
}
// CATCH BLOCK HERE.
The catch block is where you define what exceptions you want to handle.
// CATCH BLOCK
catch(MyException const& e)
{
// Correct a MyException
}
catch(std::exception const& e)
{
// Correct a std::exception
// For example this would cat any exception derived from std::exception
}
You can have as many catch blocks as you like. If you exception matches any of the catch expressions in the catch statement then the associated block of code is executed. If no catch expressions matches an exception then the stack is unwound until it finds a higher level catch block and the processes is repeated (this can cause the application to exit if no matching catch block is found).
Note: If multiple catch expressions match then the lexically first one is used. Only one or none of the catch blocks will be executed. If none then the compiler will look for a higher level try/catch.
There is also a catch anything clause
catch(...)
{
// This is a catch all.
// If the exception is not listed above this will catch any exception.
}
So how does this apply to your code.
int main( )
{
char *ptr;
try
{
// This calls ::new() which can potentially throw std::bad_alloc
// If this happens then it will look for a catch block.
ptr = new char[ 1000000000 ];
// If the ::new() works then nothing happens and you pointer `ptr`
// is valid and code continues to execute.
}
catch( … )
{
// You only have one catch block that catches everything.
// So if there are any statements that generate an exception this will catch
// the excetption and execute this code.
cout << "Too many elements" << endl;
}
// As you have caught all exceptions the code will continue from here.
// Either after the try block finishes successfully or
// After an exception has been handled by the catch block.
return 0;
}
Try-catch blocks are used to trap errors in the code.
At the most basic level, errors occur because the program tries to execute an invalid instruction. That instruction (read: line of code) could be invalid for a number of reasons. In your specific instance, the instruction could be invalid if your program was not able to allocate 1,000,000,000 bytes of memory to story your ptr. The most common exception is trying to access a bad pointer, which is called a Null Pointer Exception, which occurs when you try to perform some action on an Object that either has not been created, or has been deleted (or got corrupt). You will learn to hate that exception.
Using catch(...) tells the program to execute the code inside the catch block if any error occurs inside the code within the try block. There you can handle your error and try to find someway to either fix the error condition or gracefully exit that module.
You can also catch specific errors, which you can find out more about here : http://www.cplusplus.com/doc/tutorial/exceptions/
If you already know C, try/catch achieves the same thing as setjmp/longjmp when used for error handling. Think of try as code for the if condition of setjmp and catch code for else of setjmp. This makes longjmp equivalent to throw in C++, which is used to throw an exception. In your example, probably, the new operator, which calls some memory allocation function internally, throws an exception on seeing a very large number as input by using the C++ throw operator.
void a()
{
.......
longjmp(buf,1); // <--- similar to throw
.......
}
if ( !setjmp(buf) ) // <--- similar to try
{
.......
a();
.......
}
else // <--- similar to catch
{
.......
}
try/catch is a bit more sophisticated than setjmp/longjmp, as for setjmp/longjmp you will need to declare variables which are modified in between setjmp/longjmp calls as volatile, which is not necessary for try/catch.

intermixing c++ exception handling and SEH (windows)

I have a function in which I call getaddrinfo() to get an sockaddr* which targets memory is allocated by the system.
As many may know, you need to call freeaddrinfo() to free the memory allocated by getaddrinfo().
Now, in my function, there are a few places, where I may throw an exception, because some function failed.
My first solution was to incorporate the freeaddrinfo() into every if-block.
But that did look ugly for me, because I would have had to call it anyways before my function returns, so I came up with SEH`s try-finally...
But the problem I encountered is, that it is not allowed to code the throw-statements into the __try-block
Then, I read on the msdn and tried to swap the throw-statements into the helper function called from within the __try-block... and voila, the compiler didn´t moan it anymore...
Why is that? And is this safe? This does not make sense to me :/
Code:
void function()
{
//...
addrinfo* pFinal;
__try
{
getaddrinfo(..., &pFinal);
//if(DoSomething1() == FAILED)
// throw(exception); //error C2712: Cannot use __try in functions that require object unwinding
//but this works
Helper();
//...
}
__finally
{
freeaddrinfo();
}
}
void Helper()
{
throw(Exception);
}
EDIT:
tried the following and it works with throwing an integer, but does not when i use a class as an exception:
class X
{
public:
X(){};
~X(){};
};
void Helper()
{
throw(X());
}
void base()
{
__try
{
std::cout << "entering __try\n";
Helper();
std::cout << "leaving __try\n";
}
__finally
{
std::cout << "in __finally\n";
}
};
int _tmain(int argc, _TCHAR* argv[])
{
try
{
base();
}
catch(int& X)
{
std::cout << "caught a X" << std::endl;
}
std::cin.get();
return 0;
}
Why? :/
You can't mix the two exception types. Under the covers, C++ exceptions use SEH and your SEH exception handler could mess up the exception propogation logic. As a result, the C++ compiler won't allow you to mix them.
PS: Structured Exception Handling is almost always a VERY bad idea. Internally Microsoft has banned the use of SEH except in very limited circumstances. Any component that does use structured exception handling is automatically subject to intense code reviews (we have tools that scan code looking for its use to ensure that no cases are missed).
The problem with SEH is that it's extremely easy to accidentally introduce security vulnerabilities when using SEH.
You could wrap the addrinfo in a class that calls getaddrinfo in the constructor and freeaddrinfo in its destructor.
That way it will always be freed, whether there is an exception thrown or not.
catch(int& X)
{
std::cout << "caught a X" << std::endl;
}
That doesn't catch an X, it catches an int&. Since there is no matching catch block, the exception is uncaught, stack unwinding doesn't occur, and __finally handlers don't run.
You can put catch (...) in your thread entrypoint (which is main() for the primary thread) in order to make sure that stack unwinding occurs, although some exceptions are unrecoverable, that's never true of a C++ exception.

why does throw "nothing" causes program termination?

const int MIN_NUMBER = 4;
class Temp
{
public:
Temp(int x) : X(x)
{
}
bool getX() const
{
try
{
if( X < MIN_NUMBER)
{
//By mistake throwing any specific exception was missed out
//Program terminated here
throw ;
}
}
catch (bool bTemp)
{
cout<<"catch(bool) exception";
}
catch(...)
{
cout<<"catch... exception";
}
return X;
}
private:
int X;
};
int main(int argc, char* argv[])
{
Temp *pTemp = NULL;
try
{
pTemp = new Temp(3);
int nX = pTemp->getX();
delete pTemp;
}
catch(...)
{
cout<<"cought exception";
}
cout<<"success";
return 0;
}
In above code, throw false was intended in getX() method but due to a human error(!) false was missed out. The innocent looking code crashed the application.
My question is why does program gets terminated when we throw "nothing”?
I have little understanding that throw; is basically "rethrow" and must be used in exception handler (catch). Using this concept in any other place would results into program termination then why does compiler not raise flags during compilation?
This is expected behaviour. From the C++ standard:
If no exception is presently being
handled, executing a throw-expression
with no operand calls
terminate()(15.5.1).
As to why the compiler can't diagnose this, it would take some pretty sophisticated flow analysis to do so and I guess the compiler writers would not judge it as cost-effective. C++ (and other languages) are full of possible errors that could in theory be caught by the compiler but in practice are not.
To elaborate on Neil's answer:
throw; by itself will attempt to re-raise the current exception being unwind -- if multiple are being unwound, it attempts to rethrow the most recent one. If none are being unwound, then terminate() is called to signal your program did something bogus.
As to your next question, why the compiler doesn't warn with throw; outside a catch block, is that the compiler can't tell at compile-time whether the throw; line may be executing in the context of a catch block. Consider:
// you can try executing this code on [http://codepad.org/pZv9VgiX][1]
#include <iostream>
using namespace std;
void f() {
throw 1;
}
void g() {
// will look at int and char exceptions
try {
throw;
} catch (int xyz){
cout << "caught int " << xyz << "\n";
} catch (char xyz){
cout << "caught char " << xyz << "\n";
}
}
void h() {
try {
f();
} catch (...) {
// use g as a common exception filter
g();
}
}
int main(){
try {
h();
} catch (...) {
cout << "some other exception.\n";
}
}
In this program, g() operates as an exception filter, and can be used from h() and any other function that could use this exception handling behavior. You can even imagine more complicated cases:
void attempt_recovery() {
try{
// do stuff
return;
} catch (...) {}
// throw original exception cause
throw;
}
void do_something() {
for(;;) {
try {
// do stuff
} catch (...) {
attempt_recovery();
}
}
}
Here, if an exception occurs in do_something, the recovery code will be invoked. If that recovery code succeeds, the original exception is forgotten and the task is re-attempted. If the recovery code fails, that failure is ignored and the previous failure is re-throw. This works because the throw; in attempt_recovery is invoked in the context of do_something's catch block.
From the C++ standard:
15.1 Throwing an exception
...
If no exception is presently being
handled, executing a throw-exception
with no operand calls terminate()
The reason the compiler can't reliably catch this type of error is that exception handlers can call functions/methods, so there's no way for the compiler to know whether the throw is occurring inside a catch. That's essentially a runtime thing.
I have little understanding that throw; is basically "rethrow" and must be used in exception handler (catch). Using this concept in any other place would results into program termination then why does compiler not raise flags during compilation?
Rethrowing is useful. Suppose you have a call stack three levels deep with each level adding some context resource object for the final call. Now, when you have an exception at the leaf level, you will expect some cleanup operation for whatever resources the object has created. But this is not all, the callers above the leaf may also have allocated some resources which will need to be deallocated. How do you do that? You rethrow.
However, what you have is not rethrow. It is a signal of giving up after some failed attempts to catch and process any and all exceptions that were raised.
A throw inside of a catch block with no args will re-throw the same exception that was caught, so it will be caught at a higher level.
A throw outside of a catch block with no args will cause a program termination.
To complete the previous answers with an example of when/why the compiler cannot detect the problem:
// Centralized exception processing (if it makes sense)
void processException()
{
try {
throw;
}
catch ( std::exception const & e )
{
std::cout << "Caught std::exception: " << e.what() << std::endl;
}
catch ( ... )
{
std::cout << "Caught unknown exception" << std::endl;
}
}
int main()
{
try
{
throw 1;
}
catch (...)
{
processException(); // correct, still in the catch clause
}
processException(); // terminate() no alive exception at the time of throw.
}
When compiling the function processException the compiler cannot know how and when it will be called.
You don't have anything to catch, and so the exception bubbles all the way up. Even catch(...) needs something.