Hello
What does that mean:
And:Code:void some_function(int blabla) try { } catch (...) { }
When is it smart to define functions like that?Code:void some_function(int blabla) throw { }
Hello
What does that mean:
And:Code:void some_function(int blabla) try { } catch (...) { }
When is it smart to define functions like that?Code:void some_function(int blabla) throw { }
The first one catches exceptions thrown anywhere in the function. It's a special syntax designed for the intialization list in constructors. The second one I'm not sure about. I don't think it's legal.
The first is a function level try block. It's probably good to catch exceptions thrown in this function, to do some clearing-up (before possibly rethrowing the error).
The second should be invalid, but the aim is to specify the types of exceptions this function might throw. It is important, that the function (or an object used it) wouldn't throw any unspecified exceptions (this is the reason why it is not used much in the C++ libraries, because with templates you'll never know what exceptions one or another object might throw.
Code:void some_function() throw(std::exception); //function promises to throw only exceptions of type std::exception void another_function() throw(); // promise to throw no exceptions
The motivation for the function-level try block comes from constructors. Consider a constructor that wants to catch all exceptions. A naive approach might look like this:
As I said, it's naive. What initialization is there to do? It has all been done already, in the initializer list. If I had it written explicitly:Code:class A : public B { C c; D d; public: A(); }; A::A() { try { // do initialization } catch(...) { // handle error } }
Exceptions from the B, C and D constructors are outside the try. They're not caught.Code:A::A() : B(), c(), d() { try {} catch(...) {} }
The function-level try block looks like this:
Now the initializer list is inside the try and its exceptions can be caught.Code:A::A() try B(), c(), d() { } catch(...) {}
Making function-level try blocks available for normal functions was a matter of consistency.
Note, however, that there still is one difference: the catch block of a constructor must exit with an exception; if it doesn't throw one, the caught one is automatically re-thrown.
As for exception specifications, there is a simple and nearly universally applicable rule for their use: don't.
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law