Bad Re-throw collection but crash at runtime

The following code will compile, but fail at runtime:

int main() {

    try {
        throw;
    }
    catch(...){
        cout<<"In catch";
    }
     return 0;

}

      

Result: "Unhandled exception at 0x7c812a5b in hello.exe: Microsoft C ++ exception: [rethrow] @ 0x00000000"

Why does the compiler allow you to compile your code? it doesn't look so hard for the compiler to check if this code is part of the catch block or not.

+2


source to share


7 replies


From the C ++ standard (15.1.8)

If no exception is currently being thrown, executing a throw expression with no operands calls std :: terminate ()



As the standard allows it and gives clear semantics, the compiler can only conform to it.

+5


source


There are probably millions of bugs that compilers can catch if compiler writers put enough work into them. But it is up to these compiler authors to judge if the work is worth it. In this case, they have not decided (and I agree with them). In the meantime, there is no need to worry about it.



+5


source


Not so easy. You could call this function from within the catch block in some other function.

The concept of a so called exception handler is described in this answer .

+3


source


You can place the throw in a function that is called from within the catch block. Sometimes useful if you have general handling for an exception class:

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();
   }
}

      

+2


source


Just because the code is legal. You can say the same:

int* p=0;
*p = 0;

      

and thousands of other examples. This is legal, but very wrong.

+2


source


How do you know that the caller of the function won't catch the exception?

0


source


Thanks, I think I figured out something like throwing a null exception (there is nothing to throw around) and the compiler shouldn't be doing null checks for us.

0


source







All Articles