0

Possible Duplicate:
What is the difference between throw and throw with arg of caught exception?
Does catch (…) work on throw; with no object?

This will crash:

try
{
    if(1)
        throw;
}
catch(...)
{
    printf("hi");
}

I thought I could do that but I guess not. What is the right way to throw when you don't need any information?

Community
  • 1
  • 1
loop
  • 3,460
  • 5
  • 34
  • 57

2 Answers2

6

A "naked throw" re-throws an exception that has already been caught. Doesn't work well if there is nothing to rethrow.

You can really throw anything, like throw "Error!";, even if that is not too useful. You could otherwise try

if (x == 1)
    throw std::runtime_error("x == 1 is not a good value here")`.
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • I'm not going to use the throw information though. Is there some standard practice for that maybe like `throw std::defaultthrow`? – loop Aug 26 '12 at 19:10
  • You *should* use the exception though. `catch(...)` is basically worthless as you will have no idea how to recover from "any" exception. If you insist on a completely generic exception type though, you have the option of simple types like `throw false;`, or use the standard `std::runtime_error()`. – tenfour Aug 26 '12 at 21:05
1
#include <exception>

try
{
    if(1)
        throw std::exception();
}
catch(...)
{
    printf("hi");
}

This might be better, depending on what you are up to:

class my_exception : public std::exception {};

then,

try
{
    if(1)
        throw my_exception();
}
catch(my_exception)
{
    printf("hi");
}
Caesar
  • 9,483
  • 8
  • 40
  • 66
Jive Dadson
  • 16,680
  • 9
  • 52
  • 65