Exception out of the blue (exception on an empty space) in C++ - c++

Can a C++ exception come "out of nowhere"? Not literally. Does anybody know non obvious special cases when C++ runtime can throw exception from a place that is not an explicit call of the function?
Platform specific experiences and information about implementations that deviate from the standard are interesting also.
Please do not post answers about:
Macroprocessor tricks that hide function calls;
Default constructors;
Destructors;
Overloaded operators;
Overloaded conversions;
Unoverloaded operators new and new[];
MSVC provides an option that allows to handle hardware exceptions (GPF, division by zero, etc) as C++ exceptions. Can anybody comment on how this is handled on other platforms or maybe somebody knows a right place in the standard that speaks about this?
To the guy who downvoted this question: Please, have courage to tell what is wrong here.

No, no, and there isn't one, it's only an MSVC option. Only Windows treats hardware errors like exceptions, and these structured exceptions are only converted into C++ exceptions if you ask for it. The other platforms use signals.
Exceptions do not come out of nowhere. They come when you, or the well-defined places in the Standard library (and a couple in the language like dynamic_cast) throw them. The C++ runtime does not throw them for lolsies. If you have an exception of unknown source, then get a better debugger and learn how to use it until it doesn't have an unknown source.

Related

Prefix try keyword with two underscore in c++ [duplicate]

I came across this article about detecting VMWare or Virtual PC
http://www.codeproject.com/KB/system/VmDetect.aspx
and I saw that they use some kind of try-except statement.
So I looked it up in the MSDN: http://msdn.microsoft.com/en-us/library/s58ftw19%28v=vs.80%29.aspx
and I don't understand why would I use a try-except instead of the good old try-catch.
does it just give me additional information about the exception?
If so, I can use a try-catch when I use the code from the attached article, right?
thanks :)
__try/__except is a try/catch, for a different kind of exception. You can catch hardware exceptions like floating point violation, bad pointer de-reference, etc, and not C++ exceptions. This is referred to as Structured Exception Handling, or SEH, and MSDN has quite a bit on it if you know where to look.
In this case, they're using it to detect invalid instructions. This is where they attempt to execute instructions that x86 doesn't support, and virtual machines use them. If you're running on a real CPU, then you will get an invalid instruction exception, and if you're running on a virtual machine, you just talked to it.
MSDN is typically unclear about all of this, but the exceptions dealt with by __try/__except are not C++ exceptions, but system exceptions. Things like Segmentation Fault.
the __try and __except are part of structured exception handling, this is a different exception handling model than the standard one, as it handles hardware exceptions identically to software ones, see the link for information.
Microsoft created Structured Exception Handling for Microsoft C++ before the actual C++ standard started to include exceptions as well. On Windows, therefore, all exceptions that exist are SEH exceptions, but not all of those are C++ exceptions.
__try / __except is a way to catch SEH exceptions (and accidentally, also C++ exceptions). try/catch is the way to catch only C++ exceptions. I also recall that there's a limit to not being able to use both in one function, but it's easy to work around that.
For use, just use try/catch for any exceptions. If somebody explicitly throws you a SEH exception (divide by zero, null pointer dereference etc.), catch it and convert it to regular program flow asap, such as making it into a regular exception or halting the software.
The __try, __except and __finally clauses are for Structured Exception Handling, this is an exception handling mechanism for exceptions thrown by Windows. They're not the same as C++ exceptions.

What happens if exception gets thrown "through" c code? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Will C++ exceptions safely propagate through C code?
If you have c code, for example the png lib, with your own io handlers which are written in c++ and an exception gets thrown due to some io error. is it ok to let it go through the c code and catch it outside of the c code? i know that care has to be taken with memory leaks but typically all structures get pre-allocated.
It is entirely up to the compiler if this will work or not. None of the language standards can obviously say anything about what the other language should do.
In the best case, the exception will pass the C code and get back to the next C++ level while possibly leaking any dynamically allocated C structures. In the less good case, it will crash and burn!
One possibilty is of course to compile the C code as C++, while also checking that it is exception neutral.
The answer to your question is implementation-defined.
For GCC, as #Kerrek says, compiling the C code with -fexceptions will ensure the run-time remains consistent when an exception is thrown through C code. (Note that modern exception mechanisms are not just implemented via setjmp/longjmp; they actually unwind the stack frame by frame in order to handle destructors and try/catch blocks properly.)
However, the C code itself may not be expecting to have exceptions thrown through it. Lots of C code is written like this:
acquire a resource
do some stuff
release resource
Here "acquire a resource" could mean malloc, or pthread_mutex_lock, or fopen. If your C++ code is part of the "do some stuff", and it throws an exception, well... Whoops.
Resource leaks are not the only problem; so is correctness is general. Imagine:
subtract $100 from savings account
add $100 to checking account
Now imagine an exception gets thrown after the first step finishes but before the second one does.
In short, although your implementation may provide a way to let you throw exceptions through C code, it is a bad idea unless you also wrote that C code knowing exactly where an exception might be thrown.
It's okay for your C++ code if it's:
Compiled with exceptions enabled.
Exception safe.
It's okay for your C or C++ code if:
No resources need to be collected explicitly between the throwing of the exception, and its being caught.
Code compiled with C++ exception support adds special hooks to clean up when exceptions are thrown and not caught in that scope. C++ objects allocated on the stack will have their destructors invoked.
The only resource reclaimed in C (or C++ without exception support) when an exception is thrown is the space allocated in each stack frame.
This section of the GCC manual is quite helpful:
-fexceptions
Enable exception handling. Generates extra code needed to
propagate exceptions. For some targets, this implies GCC will
generate frame unwind information for all functions, which can
produce significant data size overhead, although it does not affect
execution. If you do not specify this option, GCC will enable it
by default for languages like C++ which normally require exception
handling, and disable it for languages like C that do not normally
require it. However, you may need to enable this option when
compiling C code that needs to interoperate properly with exception
handlers written in C++. You may also wish to disable this option
if you are compiling older C++ programs that don't use exception
handling.
Exceptions aren't usually really thrown "through" code; as the action implies, they are thrown "over" code.
As a forinstance; at least old-school Objective-C exceptions are usually implemented with setjmp and longjmp; essentially storing the addresses of code for later use.
It makes sense for C++ exceptions to be implemented with similar mechanisms; and as such; the type of code the exception is thrown "through", or more accurately, "over" matters little, if at all. One could even imagine a setting where an Objective-C exception is thrown over a C++ catch, or vice versa.
Edit: As Bo Persson mentiones; this is not to say that a C++ exception interrupting C code wouldn't cause havoc and leaks; but exceptions being thrown is usually a Bad Thing™ all round; so it's not likely to matter much.
PS: Kudos on actually asking a question where using both C and C++ tags is relevant. ;)
C doesn't know anything about exceptions so it's not possible to say what would happen.
To write conforming code you'd need to catch exceptions prior to returning into the C library, translate to error codes, and then translate the C-library error back into an exception on the other end.

Will turning off exceptions in C++ lead to undefined behavior according to the current standard?

I often hear the C++ exception system can be disabled as you should not pay for what you do not use. If I choose to compile my C++ program without exceptions will it result in undefined behavior?
The current (and future) C++ standard has no notion of turning off exceptions. So technically yes, doing so leads to undefined behavior, if you ask the language lawyers. Realistically implementations try to define reasonable behavior for this popular extension. Consult your documentation.
To add to Howard's answer.
The general issue is that code written with exceptions in mind could suddenly become bug-riddled if you turn them off.
A simple call to new for example, is supposed to throw the std::bad_alloc exception if the memory request cannot be honored. In case you turn off exceptions it'll return 0 instead: are you sure that all calls to new check that the return is not 0 ? Even those in the standard library or 3rd party libraries ?
CLang recently introduced a diagnosis that prevents compilation if throw or try are used when compiling with exceptions disabled, because it means that the code has not been properly prepared, but I am unsure wrt the other compilers, so watch out.

Revert exception specifications behavior under VC++ 9.0

I'm working on old code that relies heavily on the exception specifications behavior described in the language standard. Namely, calls to std::unexpected() on exception specification violations of the form described below.
foo() throw(T) { /*...*/ }
Nothrow specifications are indeed guaranteed to not throw, but throw(T) ones are expected to be violated both by design and... well, because the standard expects as much and provides a mechanism to handle it.
The reasons for this are tied to the designers decision of using EH also as an error handling mechanism (controlled by its own error class hierarchy) in addition to exception handling. The idiom presented in EH closely mapped to their needs and they took the path of least effort. This is at least how I see it and isn't particularly shocking to me, given the size and complexity of the system.
I'm however now tasked to include new and unrelated functionality and the code isn't behaving as expected under VC++ 9.0, due to the deviation from the standards regarding exception specifications introduced in 8.0. (reference: Microsoft)
I'm trying to find a way to force the standard behavior. Was hoping for a fallback to be offered by the compiler. But there is none.
Am I out of luck and need to change correctly written standard-obedient code running on the 350,000 lines of code with a fully developed error handling class hierarchy? Or can you think of a way that will help me to force std::unexpected() behavior?
EDIT:
I'm providing some background information. The system in question is a School Year Calendars Generator for a school serving a little over 4,000 students distributed among, I'm unsure as to some of the numbers yet, 6 grades and ~190 classes, plus 12 virtual (long-distance teaching) classes. MINGW is out of the question as is any compiler other than VC++ 8.0 or 9.0. This is due to regulations pertaining to software serving the Educational System in this country.
The changes needed to the code are exactly to accommodate the introduction of the virtual classes with a vastly different schema for calendar generation. And then I bumped into this problem. The software makes heavy use of the exceptions mechanism on a few parts of the calendar generation process as a means to control workflow through both unexpected() mappings (saved and restored) and bad_exception mappings, none of which work under VC++. On a purely personal note, I find the mechanism in place actually very elegant even if entirely uncommon. But I digress.
I don't believe that Visual C++ exception specification behaviour has ever been (or claimed to have been) standards conforming - even before 8.0 - so I'm not sure how the application has been working.
Is it feasible to perform changes such as:
void f() throw(T)
{
// ...
}
to:
void f()
{
try
{
// ...
}
catch (T)
{
throw;
}
catch (...)
{
app_unexpected();
}
}
As you mentioned, Visual Studio has an "interesting" way of dealing with exception specifications:
throw() has its normal meaning (the function must not throw)
anything else (including no exception specification) is interpreted as throw(...)
There is no way to circumvent this. However, the C++ community pretty much agrees that exception specifications are useless. Do you really need runtime checking of error types thrown? Perhaps proper unit testing can replace your runtime checks.

about c++ exceptions. func() throw()

i am reading this page http://www.cplusplus.com/doc/tutorial/exceptions.html
it says if i write function() throw(); no exceptions can be thrown in that function. I tried in msvc 2005 writing throw(), throw(int), throw() and nothing at all. each had the exact same results. Nothing. I threw int, char*, another type and it was all caught the same way. It looks like throw doesnt affect it at all. What does function() throw() actually do?
See this article for details on C++ exception specifications and Microsoft's implementation:
Microsoft Visual C++ 7.1 ignores exception specifications unless they are empty. Empty exception specifications are equivalent to __declspec(nothrow), and they can help the compiler to reduce code size.
[...] If it sees an empty exception specification, it will assume you know what you are doing and optimize away the mechanics for dealing with exceptions. If your function throws anyway - well, shame on you. Use this feature only if you are 100% positive your function does not throw and never will.
What you're finding is that that version of VC++ didn't enforce specification exceptions. I believe that was documented as a variance from the standard.
However, exception specifications are usually not a good idea. If a program violates them in a standards-conforming implementation (which the VC++ from VS 2005 was not in this case), the system is supposed to catch it. This means that the specification is not a compiler optimization hint, but rather forces the compiler to go to extra lengths, and sometimes produce suboptimal code.
See the Boost rationale for reasons why the highly regarded Boost project does not use exception specifications. This is Boost, which is something of the poster child for doing weird and useful things with advanced parts of the language.
Quoting from A Pragmatic Look at Exception Specifications:
(Mis)understandings
The second issue has to do with
knowing what you’re getting. As many
notable persons, including the authors
of the Boost exception specification
rationale, have put it,
programmers tend to use exception
specifications as though they behaved
the way the programmer would like,
instead of the way they actually do
behave.
Here’s what many people think that
exception specifications do:
Guarantee that functions will only throw listed exceptions (possibly
none).
Enable compiler optimizations based on the knowledge that only listed
exceptions (possibly none) will be
thrown.
The above expectations are, again,
deceptively close to being correct.
See the link for the full details.
Throwing an exception is not enough, you need a try {} catch() block to catch exceptions. If you don't catch exceptions, std::terminate() is called and your program exits abruptly. Take some time out and have go at this.
throw specifications are designed for two purposes:
To serve as a contract between interface implemented and interface user - you state which exceptions can be throwned from your method, some people consider it part of an interface. (contract) Ala checked exceptions in Java.
As a way to signal the compiler that it can apply certain optimizations in case no exceptions can be thrown from a method/procedure (setting up exception handling costs something)
Throwing an exception not specified in throw() clause is a mistake, however at no point is the implementation required to verify it for you. In fact it's not even possible to verify, as it includes all the possible exceptions from subroutines your subroutine calls. (possibly from other modules) It is not even possible within a single module, as is easily reduced to a halting problem :)