Bad Re-throw compiles but crash at runtime - c++

Following code will compile but crash at run time:
int main() {
try {
throw;
}
catch(...){
cout<<"In catch";
}
return 0;
}
Result: “Unhandled exception at 0x7c812a5b in hello.exe: Microsoft C++ exception: [rethrow] # 0x00000000”
Why compiler allows the code to compile? it looks not so difficult job for compiler to check if this code is part of catch block or not.

From C++ Standard (15.1.8)
If no exception is presently being handled, executing a throw-expression with no operand calls std::terminate()
As standard allows it and gives clear semantics, a compiler can only conform to it.

There are probably millions of errors that compilers could catch, if the compiler writers put enough work into them. But those compiler writers have to make judgements about whether that work is worthwhile. In this case, they decided not (and I agree with them).

Not so easy. You could have called this function from inside a catch block in some other function.
A concept of so-called exception handler is described in this answer.

You can put the throw in a function which is called from a catch block. Sometimes useful if you have a common handling for a class of exceptions:
void handleXExceptions()
{
try {
throw;
} catch (XA&) {
...
} catch (XB&) {
...
} catch (X&) {
assert("Update handleXExceptions" == NULL);
}
}
void f() {
try {
...
} catch (X&) {
handleXExceptions();
}
}
void g() {
try {
...
} catch (X&) {
handleXExceptions();
}
}

Simply because the code is legal. You could say the same about:
int* p=0;
*p = 0;
and thousands of other examples. It's legal but very wrong.

How should it know the caller of the function will not catch the exception?

Thanks, I think i got the point, it is something like throwing null exception (there is nothing to re throw) and compiler is not supposed to do null checks for us.

Related

Should Lippincott functions be declared noexcept?

EDIT: Another way to ask this question, in perspective, is to ask: Should Lippincott functions "catch all"?
Should Lippincott functions be declared noexcept?, does it matter?
After all, a version of this function in which all exceptions are captured, by definition cannot produce an exception.
However, in all the examples I see online, the noexcept is never there and I was wondering if I was missing something.
Example case:
foo_Result lippincott() noexcept???
{
try {
throw;
} catch (const MyException1&) {
return FOO_ERROR1;
} catch (const MyException2&) {
return FOO_ERROR2;
} catch (...) {
return FOO_UNKNOWN;
}
}
foo_Result foo_dothing() {
try {
foo::DoThing();
return FOO_OK;
}
catch (...) {
return lippincott();
}
}
Not all catch (...) executions come from a C++ exception. It is typically advisable to rethrow the exception in any catch-all block. This would imply that lippincott should not be noexcept and also just not have the catch-all block.
Specifically, in the ABI commonly used for C++ outside of Windows, forced unwinding may execute catch-all blocks:
A catch-all block may be executed during forced unwinding. For
instance, a longjmp may execute code in a catch(...) during stack
unwinding. However, if this happens, unwinding will proceed at the end
of the catch-all block, whether or not there is an explicit rethrow.
In particular, with GCC on Linux, the blocks are executed, and if not rethrown, the application is terminated. Forced unwinding can happen even in code you completely control on POSIX if you ever call cancellation points (e.g. read).
Aside from this, it's not uncommon for a library to execute user code (e.g. think qsort). You also usually don't want to suppress those exceptions.
Therefore, the best generic option is to be transparent in catch-all blocks. Perform the cleanup you need. Then always rethrow.
So your function would look something like:
foo_Result lippincott()
{
try {
throw;
} catch (const MyException1&) {
return FOO_ERROR1;
} catch (const MyException2&) {
return FOO_ERROR2;
} catch (const FooBaseException&) {
return FOO_UNKNOWN;
}
}
GCC does allow catching forced unwinds, so if you really wanted a catch-all and the other consideration is discarded (e.g. no user callbacks), you can first catch abi::__forced_unwind and rethrow.

What will happen is an exception is thrown while executing a throw statement

I have following code snippet:
try
{
if(/*something is true*/)
{
throw Win32Error(msgWin32Error->GetError()); //assume msgWin32Error is NULL
}
}
catch (Win32Error& win32Error)
{
}
Assuming msgWin32Error is NULL in above code snippet, when throw statement gets executed, it will have another exception in turn. What will be the behavior in such circumstance?
Thanks,
Su
There will be no C++ exception here.
You are conflating two things:
C++ exceptions (see: throw, try, catch)
Runtime errors invoked by the operating system (e.g. segmentation fault)
The latter are sometimes also confusingly called "exceptions", but you cannot catch these with C++ catch.
What will happen is that the dereference of msgWin32Error will (probably) cause the Operating System to terminate your application. Control will never even reach your throw instruction.
First of all, when you dereference a NULL pointer, you get undefined behavior. An exception might be thrown (because throwing an exception is in the list of allowable behaviors if UB is invoked), but you can't count on that. However, it's easy to construct a well defined example that gets at what I think you are asking.
char const* foo()
{
throw ExceptionZ();
return "message";
}
void bar()
{
try
{
throw ExceptionX(foo());
}
catch(ExceptionX) { ... }
catch(ExceptionZ) { ... }
}
In this case, the handler for ExceptionZ will be entered. The throw statement in bar does not complete. The exception thrown from foo() propagates before it can.

Nested catch operators

I need catch exceptions that are maybe thrown by code in try...catch construction, and do something depending on exception type. But also I want do some code if any exception are thrown.
I did so:
try
{
// code
}
catch (...)
{
try
{
throw;
}
catch (exc1)
{
// handling
}
catch (exc2)
{
// handling
}
// here is code that are executed if any exception are thrown
}
My code works, but I want to know whether the Standard says anything about it.
Maybe is there any better method?
UPD: Sorry for the slow answers to comments. Simple, English is a second language for me.
UPD: I think that code from AdelNick or second code from Steve Jessop or second code from David Rodríguez - dribeas are right for me.
Your approach is bad, because the // here is code that are executed if any exception are thrown part won't be executed if neither of exc1 or exc2 branch catch the exception. Your code is an equivalent version of the following:
try
{
// code
}
catch (exc1)
{
// handling
}
catch (exc2)
{
// handling
}
// here is code that are executed if any exception are thrown
The C++ language does not support a finally block, if that's what you're after. That is because an object's destructor is responsible for freeing resources, not a finally block. Here is Stroustrup's explanation of the topic.
You should write:
try
{
// code
}
catch (exc1)
{
// handling
}
catch (exc2)
{
// handling
}
catch (...)
{
// here is code that are executed if any *other* exception are thrown
}
If you want particular code to be executed as part of all three cases then you have two options: call it in all three places, or do something like this:
bool threw = true;
try
{
// code
threw = false;
}
catch (exc1)
{
// handling
}
catch (exc2)
{
// handling
}
catch (...) {
}
if (threw) {
// here is code that are executed if any exception are thrown
}
I would change the code order as following:
try
{
try
{
// code
}
catch (exc1)
{
// handling
throw; // edited. was: throw exc1;
}
catch (exc2)
{
// handling
throw; // edited. was: throw exc2;
}
}
catch(...)
{
// here is code that are executed if any exception are thrown
}
as it works if any other type of exception is thrown (not only exc1 or exc2). Also if the code common for all exceptions is the resource releasing, consider using RAII principle instead).
Looking at the comments it seems that you may be expecting something that won't happen, and that has already been discussed in other answers. But it could be a misunderstanding on our side. If the code inside the try can only throw one of exc1 or exc2 then yes, it will do what you expect.
From the comment update, it seems that the intention was to handle any exception, including those that are neither exc1 nor exc2. For that purpose, the code won't do what is expected and exc3 will propagate outside of the nested trys. Just flatten the two levels and add a catch (...) at the end.
From here on the answer was based on a false assumption about the question.
The pattern of rethrowing is supported by the standard and used commonly in situations where the handling of the exceptions in different contexts is the same to avoid code duplication:
void processException() {
// implement exception handling in all contexts
try {
throw;
} catch (exceptionType1 const & ex1) {
} catch (exceptionType2 const & ex2) {
// } catch (...) {
}
}
void f() {
try {
something();
} catch (...) {
processException();
}
}
void g() {
try {
anotherThing();
} catch (...) {
processException();
}
}
If the code to handle the exceptions is not going to be centralized for different functions, that pattern may complicate the code more than you need. You could consider a single try/catch with an extra control variable:
bool success = false;
try {
doSomething();
success = true;
} catch (exception1 const & ex1) {
...
} catch (exception2 const & ex2) {
...
// } catch (...) {
}
if (!success) {
// common code to all exceptions
}

c++ exception handling

Learning "try & catch". What is wrong with the following code?
Thanks for the advice.
Error in execution:
terminate called without an active exception
Aborted
The code:
#include <stdio.h>
int main()
{
int a = 3;
try
{
if (a < 5)
throw;
}
catch (...)
{
printf ("captured\n");
}
return 0;
}
Your throw; statement tries to rethrow a current exception but there probably isn't one. You need something like
throw some_exception_object();
Inside of a try block, you have to specify what to throw. The only place you can use throw by itself is inside of a catch block to re-throw the current exception. If you call throw by itself without a current exception being active, you will kill your app, as you have already discovered.
Try this:
#include <stdio.h>
int main()
{
int a = 3;
try
{
if (a < 5)
throw 1; // throws an int
}
catch (...)
{
printf ("captured\n");
}
return 0;
}
You can throw anything you want, as long as you throw something.
There are four things, two major and two minor. One thing at a time...
1. Rethrow usage w/o active exception
A throw; statement is used to re-throw an exception that is currently caught. For example:
try {
do_something();
} catch (const std::exception &) {
throw; // This statement re-throws an exception that was caught in this "catch" block.
}
In your case, you are using throw; without catching any exceptions (in order words — it does not appear inside catch block directly or indirectly), thus your program is terminated. When there is a need to throw and not to re-throw an exception, like in your case, you must specify an exception object to be thrown. For example:
throw std::runtime_error("Something bad happened");
2. catch-all clause which does not re-throw a caught exception
Your catch-all clause (catch (...)) is perfectly legal C++. However, it does not re-throw caught exception. Even though it is a legal C++ code, such a usage is a taboo. C and C++ runtime is usually using special types of exceptions to implement certain functionality. For example, NPTL is using exceptions to implement a thread cancellation. If you catch that exception using catch (...), a thread won't be cancelled and you are going to have a bad time. Generally, you have to catch exceptions by their types. In almost all cases, exceptions are inherited from std::exception, and so you have to write catch (const std::exception &) or, if you expect to catch an exact type, - catch(const TypeYouExpect &). If you must, however, use catch-all, remember to re-throw. For example:
try {
do_something();
} catch (...) {
throw; // DO NOT FORGET TO RE-THROW.
}
3. Header naming...
You are including C header whereas C++ provides its own headers for standard C features. So, header:
#include <stdio.h>
.. should be:
#include <cstdio>
C++ specific C functions get special treatment. For example, they become available in std namespace. So that you can use std::open() instead of just open() or ::open(). No big deal, but is highly recommended way to go.
4. Return from main.
Unlike C, C++'s main() function is very special. It allows you not to have return 0;. This is a default behavior. So, unless you really need to return some value, you may save yourself some time by not typing return 0;. Remember, however, that main is the only function like that, and that everywhere else you must explicitly return something unless a function is marked void.
Hope it helps. Good Luck!
You need to actually throw some object. Even something as simple as
throw "error";
will catch the error like you want it to.
see it in action here
The statement to throw an exception is:
throw <expression>;
This statement:
throw;
is also called the re-throw statement and is use to re-throw an existing exception that has been caught. It is typically used in a catch block, for example, you look at the exception and decide if you can continue, retry or abort. In case you decide to abort, you re-throw the exception so that somebody else down the call stack will catch it and handle this error.
For example:
// getResult() calls can fail with a deadlock exception
// This method will retry up to 3 times before failing
Result getResultWithRetry()
{
int nbTry = 3;
for(;;) {
try {
return getResult();
} catch (DeadLockException& e) {
if (nbTry == 0) {
throw; // re-throw the deadlock exception
}
}
--nbTry;
}
}

what does "throw;" outside a catch block do?

I just stumbled this code:
void somefunction()
{
throw;
}
and I wonder: what does it mean?
The intent is probably that somefunction() is only ever called from inside some catch block. In that case, there would be an exception active when the throw; is executed, in which case the current exception is re-thrown, to be caught by the next outer handler that can handle that exception type.
If throw; is executed when an exception is not active, it calls terminate() (N4810, §[expr.throw]/4).
It re-throws the currently active exception. It would only make sense to call it (possibly indirectly) from a catch-block. This:
#include <iostream>
using namespace std;
void f() {
throw;
}
int main() {
try {
try {
throw "foo";
}
catch( ... ) {
f();
}
}
catch( const char * s ) {
cout << s << endl;
}
}
prints "foo".
For throw the concept of being "outside" or "inside" catch block is defined in run-time terms, not in compile-time terms as you seem to assume. So, if during run-time that throw is executed in run-time context of a catch block, then throw works as expected. Otherwise, terminate() is called.
In fact, if you take a closer look at how C++ exceptions are defined in the language specification, a lot of things about them are defined in run-time terms. Sometimes it even appears to be un-C++-like.
People have already explained what it means but it's potentially useful to know why you might see it. It's a useful way to construct a 'generic' exception handler that deals with exceptions based on their type so as to reduce the amount of duplicated code.
So, if we take Neil's example and expand on what f() might be doing we might end up with an implementation which does something like my LogKnownException() function that I proposed in this answer.
If you are working in an team that likes to log all manner of exceptions all over the place then rather than having a huge collection of catch blocks at all of these places (or even worse a macro) you can have a simple catch block that looks like this
catch(...)
{
LogKnownException();
}
Though I expect I'd change my previous example of LogKnownException() to one that simply allowed exceptions that it didn't want to log to propagate out and continue on in an unhandled fashion.
I'm not suggesting that this is necessarily a good thing to do, just pointing out that this is where you're likely to see the construct used.