std::exception's what() returns "std::exception" - c++

Java person here stuck doing some c++. I'm catching an exception and trying to diagnose where it is coming from (regrettably the exception is not thrown when run via gdb). However, when I print out the what() of the exception I simply get the string "std::exception". Is this specific to anything in the standard library or do lots of standard exceptions return this? Here is what I am doing to print:
} catch (const std::exception & ex) {
std::cout << ex.what() << std::endl;
}
The output is just:
std::exception
Also, I'm working in a fairly large code-base, it is possible that this is coming from some exception on our end but I have yet to find it through regular search techniques so I'm currently leaning towards this coming from the standard libraries.
I'm using g++ 4.8 if that is relevant.

This could be because of two things:
Someone just does throw std::exception() somewhere, which is not very helpful.
A class derived from std::exception gets copied to std::exception. This is a problem called Object Slicing.
I just made the second mistake myself actually. I had this code:
try
{
// Some Boost stuff
}
catch (std::exception e)
{
cerr << e.what() << endl;
}
You must make sure to do std::exception& e. I know you didn't make this mistake but it's possible someone else did further within the code (or someone coming here from Google).

C++ exceptions are completely different from Java exceptions.
The C++ standard specifies that the string returned by what() is completely arbitrary, and implementation-defined:
virtual const char* what() const noexcept;
Returns: An implementation-defined ntbs.
Remarks: The message may be a null-terminated multibyte string
(17.5.2.1.4.2), suitable for conversion
and display as a wstring (21.3, 22.4.1.4). The return value remains
valid until the exception object
from which it is obtained is destroyed or a non-const member
function of the exception object is called.
The return value you're getting, "std::exception" is perfectly compliant with the C++ standard.
Don't rely on C++ exceptions to tell you exactly where they were thrown from after you catch them, like Java does. This is outside of the scope of the C++ standard. In C++, an exception is really nothing more than a mechanism for transferring execution control flow.
Having said that: many C++ implementation will provide you with some implementation-specific mechanisms for dumping the current stack backtrace, to the best of the runtime library's abilities. Check your C++ compiler's documentation for more information.
gcc, for example, offers backtrace(), together with some gcc internal functions to convert the raw addresses returned by backtrace() into symbols, and other functions for demangling the symbols. Using that, a rough analogue to Java's exception handling can be concocted; although gcc's implementation isn't perfect, and has some functional holes, and that also requires advance planning, and custom exception classes whose constructors capture the current stack frame (before the exception gets actually thrown); and, once caught, the thrown exception class instance can be inspected for the captured backtrace information.
But that doesn't really help your current situation. I would suggest that you check your C++ compiler's documentation, as I suggested, and also investigate your debugger's capabilities. A C++ debugger should allow you to set a breakpoint when any exceptions get thrown, and before it is caught, so that you can examine the stack backtrace via the debugger, when the exception occurs.

Related

Reasoning behind C++ active exception mechanism

I recently learned that in C++ there is a single "slot" for an active exception and this raise some questions for me.
The example that I know is something like:
void f()
{
MyClass c;
throw MyException;
}
When we get to the throw the function immediately returns and then the exception starts looking for its matching catch. But let's say that during the return of f, when the destructor of c is called, suppose it throws another exception of type MyException2, in this case from what I understood the program always crashes because there is only one "slot" for an active exception so when MyException2 occurs there is a problem.
I would like to know if there is a reason for this specific approach since most other languages have some sort of stack and give a message like During handling of this exception this other exception occurred, with clear stack traces for both exceptions.
Is there a reason for this problem not being approached? Things like a stack of active exceptions and if MyException2 occurs while MyException1 is active then it will just resolve and then return to the handling of MyException1?
I'm sorry if I may not be familiar with the proper terms, this is a purely education question from someone who wishes to know more about the "guts" of the language out of pure fascination.
What you’re thinking about in, say, Python looks like
try: risky()
except Error as e:
some_cleanup(e)
also_risky() # raises OtherError
if still_unhappy(): raise
more_handling()
The corresponding code in C++ behaves the same way and does not automatically terminate:
try {risky();}
catch(const Error &e) {
some_cleanup(e);
also_risky(); // throws OtherError
if(still_unhappy()) throw;
more_handling();
}
The reason is that the original exception might or might not have been handled successfully (is more_handling necessary, or is it just part of retrying?). C++ makes the optimistic statement that it was, whereas by default Python 3 makes the pessimistic statement that the new exception is fallout from the old. C++ could of course provide a syntax to indicate the other choice, like Python does (raise new from None), but such an “associated exception” would be more difficult still to deal with in a static-typing context than exceptions already are, and one of the main motivations is absent since C++ expects the program to provide whatever backtrace-reporting mechanisms are desired.
The parallel is stronger if you consider destructors in both languages (especially in CPython where many of them are reliably invoked during stack unwinding): here, Python simply prints to standard error if a destructor throws, because to do otherwise would greatly complicate its internal resource management. C++ is actually more permissive in that a destructor can throw so long as it was not invoked directly by the unwinding mechanism; this is dangerous, but is occasionally used by experts to good effect. On the other hand, C++ most certainly does not consider writing to standard error a sufficient option for handling an exception, so if its resource management encounters such a problem, it’s all over.

How to use std::exception -- stack trace plus memory leak

I am trying to figure out the best way to deal with exceptions.
C++ says that any datatype can be thrown as an exception, but there is no way to tell what data type has been thrown, which makes exceptions essentially worthless. However, I am assuming that these days everyone throw std::exception, so that is safe in a catch. Is that a fair assumption?
(I am building a library that will be used by others, so has to fit in with other code that I do not control.)
The Exception.what function returns a char * (not a string) with no way to free it. Of course, that string should contain information about the exception, for example if a file is not found then the name of the file that was not found. I assume that we just tolerate a small memory leak here when exceptions are thrown. Correct?
It is unclear how reliably stack traces can be generated in a general way and sent to a log file. (In a production environment when things go wrong, not in a debugger.) So I was thinking of inserting otherwise redundant try/catch blocks at interesting places in the code which can add logging and append extra information to the what text and then rethrow a new exception. But that process will, of course, destroy any stack trace. For example
foo = stuff();
try {
processStuff()
} catch (std::exception& ex) {
string msg = "While processing " + foo.toString() + ": " + ex.what;
log << msg;
throw std::exception((char[])msg);
}
Is that the best approach?
There are lots of articles that describe the basic classes but nothing I could find on how to really make them work in practice. Links appreciated.
(Here again I am trying to write Java/.Net in C++. Is that a hopeless cause?)
Type of exception
What type of exception object can be thrown is part of the function / method's public contract.
Often, libraries may introduce their own exception types which may or may not inherit from std::exception.
Recommended: throw std::exception or an exception inherited from it. Document the type(s) of exception thrown. Usually, you will have a "library default", such as
Unless stated otherwise, all methods and functions in this library may throw an exception of type mylib::exception or a type inherited from it.
char * what()
The (implied?) assumption is that the pointer is valid as long as the exception object is valid. No necessity to free the string manually, no reason for leak.
If you need to store the text for later, make a copy of it - e.g. by assigning to std::string.
Stack traces
... are not part of the C++ standard. Furthermore, most compiler implementations allow generating code that does not allow re-discovering a stack trace. (the respective option usually says something about "stack frame").
However, for most compilers, libraries exist that can add this stack trace, but this usually requires access to the debug symbols.
"Redundant" try/catch
You might need them anyway.
The perfect exception must support different aspects:
it contains instructions or hints for the end user how to remove a blocking issue ("Cannot open file bibbit.txt because it is read only")
it contains information for support and development why the error occurred, allowing them to possibly avoid it / handle it better in the future. (Such as ... the stack trace)
it needs to allow calling code to detect known exceptions and handle them specifically (e.g. the file the user wants to open is read-only, ask user if they want to open in read-only mode, and try again)
Rarely an exception does all that perfectly. But repackaging at certain "layers" helps a lot here - even though this makes us lose some of the beauty of exceptions.
Does that help?
Edit regarding your edit:
Generally ok, but DO NOT re-construct the exception. Change your code to:
...
catch (std::exception& ex) {
string msg = "While processing " + foo.toString() + ": " + ex.what;
log << msg;
throw; // <--- !!!!!!
}
This re-throws the original exception, so catch handlers further down can still distinguish the different types:
void Foo() {
class random_exception : public std::exception { ... }
try {
...
if (rand() % 2) throw random_exception();
...
}
catch(std::exception const & x)
{
log << x.what();
throw;
}
}
int main()
{
try {
Foo();
}
catch(random_exception const & x)
{
cout << "A random exception occurred, you can try again";
}
catch(std::exception const & x)
{
cout << This didn't work. " << x.what();
}
catch(...) // catches all exception types, but you don't know what
{
cout << "Uh, oh, you are doomed.".
}
}
Of course, that's an issue when repackaging the exception.
Some things I'm leaning to:
The exception type to be thrown is a thin wrapper around a (smart) pointer. This allows storing exceptions (e.g. to pass them to another thread, or as an "inner exception" when repackaging) without losing type information:
I allow separate messages for end user and for diagnostics. End user message is required, diagnostics is usually generated from (and contains) the error code and context. User will see no "weird numbers and techie gibberish" unless they click on "details".
Instead of including parameters in the error message:
msg = "Could not open file bibbit.txt (tried 5 times)"; // :-(
I use a fixed message, and a list of (name, value) parameters.
msg = "Could not open file"; // :-)
msg.Add("filename", filename).Add("retries", retryCount);
This should simplify localization, and allows the caller to access individual attributes for known errors, allowing more specific handling.
However, I am assuming that these days everyone throw std::Exception, so that is safe in a catch. Is that a fair assumption?
That's mostly a safe assumption. Some people insist in throwing random stuff, but it's not your business - if you are a library you throw exceptions and at most you catch your own, you shouldn't be concerned with what other people throw (your code should use RAII anyway to avoid resource leaks - this covers even the case where e.g. callbacks throw stuff you don't know).
The Exception.what function returns a char * (not a string) with no way to free it. Of course, that string should contain information about the exception, for example if a file is not found then the name of the file that was not found. I assume that we just tolerate a small memory leak here when exceptions are thrown. Correct?
Nope. The string returned by what normally does not result in a memory leak. Either is statically allocated (I've seen many simple exception classes that just return a string literal) or it's managed inside the exception itself (std::runtime_error normally contains an std::string, with what returning the result of its c_str method). In general, you can assume that whatever what results is there as long as the exception lives - if you need it outside the catch block copy it into an std::string or something.
This is actually required by the standard:
The return value remains valid until the exception object from which it is obtained is destroyed or a non-const member function of the exception object is called.
(C++11, §18.8.1 ¶10)
It is unclear how reliably stack traces can be generated in a general way and sent to a log file. (In a production environment when things go wrong, not in a debugger.) So I was thinking of inserting otherwise redundant try/catch blocks at interesting places in the code which can add logging and append extra information to the what text and then rethrow a new exception. But that process will, of course, destroy any stack trace.
Stack traces in C++ are a sad story; there's no portable way to generate them, you have to resort to platform-specific calls (or to libraries that abstract them); personally I used several approaches in the past:
on a new, multi-platform Qt application I wrote my own "fat" exception class, which saved the stack trace (I derived from booster::exception, which already bundles the stack trace-saving part) and added the possibility to add extra information while the exception gets caught and rethrown, similar to how Boost.Exception is implemented (important: Boost.Exception != booster::exception, they are completely unrelated); see here, it's full of Qt types but you can get the idea;
on a legacy project which throw the most bizarre types (and there's no way to change them to a common exception type) I just hooked (via linker tricks) the throw and I always save the stack trace in a global circular buffer, which is printed out if an exception is not caught.
Your approach is flawed because not only it loses parts of the stack trace, but even the type information about the exception. Look up how Boost.Exception does its thing to see how to do it right. Also, you never, ever throw a new (=heap allocated) exception, otherwise freeing it becomes a burden to people who want to catch it (also, probably nobody will catch it because no one catches by pointer, you normally catch by reference).
It looks like std::stack_trace will be part of C++ 23.
Under GCC (yes, I know, not universal), you can use std::current_exception to get information about the current exception. For instance, the following code will return the mangled name of the exception type:
std::string current_exception_type()
{
std::string result;
if (std::current_exception())
{
auto p = std::current_exception().__cxa_exception_type();
if (p)
{
result = p->name();
}
}
return result;
}
To demangle the name, you can use:
std::string demangle_cpp(char const* name)
{
std::string result;
char* demangled(nullptr);
try
{
int status;
demangled = abi::__cxa_demangle(name, 0, 0, &status);
if (demangled != nullptr) result = demangled;
} catch(...)
{
}
if (demangled != nullptr) free(demangled);
return result;
}

How to catch the null pointer exception? [duplicate]

This question already has answers here:
Catching access violation exceptions?
(8 answers)
Closed 6 years ago.
try {
int* p = 0;
*p = 1;
} catch (...) {
cout << "null pointer." << endl;
}
I tried to catch the exception like this but it doesn't work,any help?
There's no such thing as "null pointer exception" in C++. The only exceptions you can catch, is the exceptions explicitly thrown by throw expressions (plus, as Pavel noted, some standard C++ exceptions thrown intrinsically by standard operator new, dynamic_cast etc). There are no other exceptions in C++. Dereferencing null pointers, division by zero etc. does not generate exceptions in C++, it produces undefined behavior. If you want exceptions thrown in cases like that it is your own responsibility to manually detect these conditions and do throw explicitly. That's how it works in C++.
Whatever else you seem to be looking for has noting to do with C++ language, but rather a feature of particular implementation. In Visual C++, for example, system/hardware exceptions can be "converted" into C++ exceptions, but there's a price attached to this non-standard functionality, which is not normally worth paying.
You cannot. De-referencing a null-pointer is a system thing.
On Linux, the OS raises signals in your application. Take a look at csignal to see how to handle signals. To "catch" one, you'd hook a function in that will be called in the case of SIGSEGV. Here you could try to print some information before you gracefully terminate the program.
Windows uses structured-exception-handling. You could use the instristics __try/__except, as outlined in the previous link. The way I did it in a certain debug utility I wrote was with the function _set_se_translator (because it closely matches hooks). In Visual Studio, make sure you have SEH enabled. With that function, you can hook in a function to call when the system raises an exception in your application; in your case it would call it with EXCEPTION_ACCESS_VIOLATION. You can then throw an exception and have it propagate back out as if an exception was thrown in the first place.
There is a very easy way to catch any kind of exception (division by zero, access violation, etc.) in Visual Studio using try -> catch (...) blocks.
A minor project tweaking is enough. Just enable the /EHa option in project settings. See Project Properties -> C/C++ -> Code Generation -> Modify the Enable C++ Exceptions to "Yes With SEH Exceptions". That's it!
See details here:
http://msdn.microsoft.com/en-us/library/1deeycx5(v=vs.80).aspx
Dereferencing a null (or pointer that's past-the-end of array, or a random invalid pointer) results in undefined behavior. There's no portable way to "catch" that.
C++ doesn't do pointer checking (although I suppose some implementations could). If you try to write to a null pointer it is most likely going to crash hard. It will not throw an exception. If you want to catch this you need to check the value of the pointer yourself before you try to write to it.
Generally you can't. Even if you could it would be like trying to put a band aid on a submarine that has sprung a leak.
A crippled application can do far more damage than one that has crashed. My advice here would be to let it crash then fix why it crashed. Rinse. Repeat.
As others have said, you can't do this in C++.
If I can make a broader point: even in a language that allows you to catch it, the better action is to not touch null pointers. Catching an error when it's already blown up in your face, then deciding to just move on like it didn't happen, is not a good coding strategy. Things like null pointer dereference, stack overflow, etc., should be seen as catastrophic events and defensively avoided, even if your language allows you to react to it differently.
There is no platform independent way to do this. Under Windows/MSVC++ you can use __try/__except
But I wouldn't recommend doing it anyway. You almost certainly cannot recover correctly from a segmentation fault.
If you wanted to you could just do the pointer checking yourself and throw...
if (p == nullptr) throw std::exception("woot! a nullptr!")
p->foo();
so course this would only be to debug the problem, the nullptr should not occur in the first place :)
Short answer- you can't in a portable or standard way, because bugs like this are potentially corrupting the process itself.
Long answer- you can do more than you might think, and definitely more than the default of the program just crashing. However, you need to keep 3 things in mind:
1) These bugs are MORE severe than exceptions and often cannot present as exceptions to your logic.
2) Your detection and library handling of them WILL be platform-dependent on the back end, even though you can provide a clean abstract interface for public consumption.
3) There will always be some crashes that are so bad you cannot even detect them before the end.
Basically, faults like segfaults or heap corruption are not exceptions because they're corrupting the actual process running the program. Anything you coded into the program is part of the program, including exception handling, so anything beyond logging a nice error message before the process dies is inadvisable in the few cases it isn't impossible. In POSIX, the OS uses a signaling system to report faults like these, and you can register callback functions to log what the error was before you exit. In Windows, the OS can sometimes convert them into normal-looking exceptions which you can catch and recover from.
Ultimately, however, your best bet is to code defensively against such nightmares. On any given OS there will be some that are so bad that you cannot detect them, even in principle, before your process dies. For example, corrupting your own stack pointer is something that can crash you so badly that even your POSIX signal callbacks never see it.
In VC++ 2013 (and also earlier versions) you can put breakpoints on exceptions:
Press Ctrl + Alt + Delete (this will open the exception dialog).
Expand 'Win32 Exceptions'
Ensure that "0xC0000005 Access Violation" exception is checked.
Now debug again, a breakpoint will be hit exactly when the the null dereference happened.
There is no NULL pointer exception exist in c++ but still you want to catch the same then you need to provide your own class implementation for the same.
below is the example for the same.
class Exception {
public:
Exception(const string& msg,int val) : msg_(msg),e(val) {}
~Exception( ) {}
string getMessage( ) const {return(msg_);}
int what(){ return e;}
private:
string msg_;
int e;
};
Now based on NULL pointer check it can be threw like , throw(Exception("NullPointerException",NULL));
and below is the code for catching the same.
catch(Exception& e) {
cout << "Not a valid object: " << e.getMessage( )<< ": ";
cout<<"value="<<e.what()<< endl;
}

Is there an occasion where using catch all clause : catch (...) is justified?

Each time I have seen the catch all statement:
try
{
// some code
}
catch (...)
{
}
it has always been an abuse.
The arguments against using cache all clauses are obvious. It will catch anything including OS generated exceptions such as access violations.
Since the exception handler can't know what it's dealing with, in most cases the exceptions will manifest as obscure log messages or some incoherent message box.
So catch(...) seems inherently evil.
But it is still implemented in C++ and other languages (Java, C#) implements similar mechanisms. So is there some cases when its usage is justified?
(1) It's not true that the statement will catch OS exceptions. Your use of the term "Access Violation" betrays a Windows background; it was true for older MSVC++ versions.
(2) Regardsless, the catch-all behavior is useful for threads with specific purposes. Catching the failure allows the thread to report it failed. Without it, the other parts of the program need to deal with the possibility of a thread just disappearing. It also allows you to log which thread failed, and the arguments used to start the thread.
The case where it's justified in general is when you log the exception (or do something similar) or do some cleanup, and then immediately rethrow.
In C++ in particular, logging in a catch(...) block is pretty pointless since you don't have any way to obtain the exception, and cleanup is pointless because you should be using RAII for that. Using it in destructors seems to be about the only legitimate case.
the arguments against using cache all clauses are obvious , it will catch anything including OS generated exceptions such as access violation. since the exception handler can't know what its dealing with, in most cases the exceptions will manifest as obscure log message or some incoherent message box.
And if those same exceptions aren't caught you get... an incoherent message box.
catch(...) lets me at least present my own message box (and invoke custom logging, save a crash dump, etc.).
I think there are also reasonable uses of catch(...) in destructors. Destructors can't throw--well, I mean, they can throw, but if a destructor throws during stack unwinding due to an in-progress exception the program terminates, so they should not ever allow exceptions to escape. It is in general better to allow the first exception to continue to be unwound than to terminate the program.
Another situation is in a worker thread that can run arbitrary functions; generally you don't want an unceremonious crash if the task throws an exception. A catch(...) in the worker thread provides the opportunity for semi-orderly clean-up and shutdown.
In addition to what other posters have already said, I'd like to mention one nice point from the C++ Standard:
If no matching handler is found in a
program, the function std::terminate()
is called; whether or not the stack is
unwound before this call to
std::terminate() is
implementation-defined.
(15.3/9)
This means that main() and every thread function must be wrapped in a catch-all handler; otherwise, one can't even be sure that destructors for automatic objects will be called if an uncaught exception is thrown.
try {...} catch (...) is needed around body of callback function which is called from code
that doesn't understand C++ exceptions (usually C library).
Otherwise, if some C++ library you use throws an exception that doesn't derive from
std::exception, it will probably cause calling code to crash or corrupt its internal state.
Instead you should catch this exception and either finish program immediately or
return some error code (meaning "we are doomed and I don't know why", but it's still better
then letting C++ exception to pass through).
Around thread procedure. Mostly because of the same reason as 1.
And because otherwise thread failure would pass unnoticed.
catch(...) has been useful for me in two circumstances, both of which are unjustified (I can't even remember the second)
The first is my overall application safety. While throwing exceptions that don't derive from std::exception is a No-No, I have one just in case in my main() function:
int execute(void); // real program lies here
int main(void)
{
try
{
return execute();
}
catch(const std::exception& e)
{
// or similar
std::cerr << "Unhandled exception: " << e.what() << std::endl;
return EXIT_FAILURE;
}
catch(...)
{
std::cerr << "Unknown exception!" << std::endl;
return EXIT_FAILURE;
}
}
Now, it's only there "just in case", and it's not really justified. There should be no reason to ever enter that catch clause, as that would mean somebody has done a Bad Thing. Observe how useless the statement really is; "Something bad happened, no clue what!" It's only a step above just crashing in the first place.
The second use might be in destructors or some other function that needs to do manual management before letting the exception propagate. That's not really a justification either, as things should clean themselves up safely with RAII. But I may have used it once or twice for some reason I can't recall, and I can't see a reason to ever do so again.
catch (...) allows you to write code in which you can legitimately claim a guarantee that your code will not crash even when you are not in long term complete control of the submodules your code depends on. Your claim is tantamount to claiming that this semantic cannot be used except as a means of abuse. Maybe so, but military specifications may differ from you on this issue.
catch(...) is necessary in the absence of the finally clause as found in other languages:
try {
...
} catch(...) {
cleanup...
throw;
}
The alternative - making stack objects to 'own' everything - is often much more code and less readable and maintainable. The platform API is often C, and does not come with it conveniently bundled.
It is also useful around plugin code that you do not control or simply do not trust from a stability perspective. It won't stop them crashing, but it might keep things a little saner.
Finally, there are times when you really do not care about the outcome of something.

Using only std::exception in exception specification

It seems it is general accepted that exception specifications are not helping as much as one thinks. But I wonder if a specification which only uses std::exception might be a good compromise:
void someFunction()
throw ( std::exception );
It documents the fact that this method/function might throw an exception.
It would make sure that only exceptions derived from std::exception are thrown and not some exotic classes like std::string or int.
So, would this be better then not having any specification at all?
Update:
Regarding the Runtime-Overhead: Think of it like the usage of asserts. You are using asserts regardless of the runtime-overhead, right? I know you usually can disable them for a release-build, so maybe a better approach would be to wrap the exception specification in a macro so you can disable it for a release build. Something like:
#ifdef DEBUG
#define THROW( exception ) throw ( exception )
#else
#define THROW( exception )
#endif
void someFunction()
THROW( std::exception );
Yes but what do you expect to happen when something that is not derived from std::exception is thrown?
Would you like the application to terminate.
No stack unwinding not destructors being called to tidy up the code, just the application exiting.
The difference between Java and C++ exception specifications is that Java checks the specifications at compile-time. C++ on the other hand does all the checking at run-time. So by the time your specifications have been violated it is already too late.
Even in Java code there is a movement to stop to using them. What tends to happen there is at the start of the project the exception specifications are tightly defined. But as the code grows and becomes more complex the specifications are diluted to a more and more general form. This is because as the code grows more exceptions can be thrown and if they can not be handled immediately you need to modify the exception specifications of the whole call chain back to the point where they can be handled. (Note I am not a Java Expert but I do play in a mature Java code base).
The only exception specification (I think) that is worth much is the no throw specification. This does have a valid application (but you have to use it with the try/catch(...) block).
Also read Herb Sutters article:
And this thread on SO: Should I use an exception specifier in C++?
Exception specifications are essentially useless. Martin York already linked to Herb Sutter's post about them, but in short, you run up against the following problems:
They're ignored by MSVC, and
Their effect is nothing like in
Java. The specifications are checked
at runtime, causing a performance
hit, witout giving you the
compile-time validation you get in
Java. All you're saying is "Insert extra code, such that when an
exception is thrown, its type is inspected, and then
either throw it as normal, or call
unexpected() instead.
So all you're doing is making it harder to catch the exceptions that may be thrown, while at the same time slowing down your program. There really isn't much point.
On a conforming compiler, adding a non-empty exception specification generates the equivalent of a try/catch block around the function. Although it's possible to implement this in a way that has no run-time overhead, on some current compilers you do get an overhead.
So there may be a cost, and all you gain is that, if someFunction or something it calls raises on non-std::exception-derived exception, std::unexpected is called, rather than the unhandled exception mechanism.
So I guess my answer's 'No' :-)
I tipically would do this:
void someFunction() /* throw (std::exception) */;
The only effect of the throw statement in the function declaration is to modify its signature: a pointer to "void x()" and a pointer to "void x() throw y" are two different types.
In this way you are still documenting that the function might throw something, and you are losing nothing since the c++ compiler does not enforce any constraint anyway.