tags:

views:

134

answers:

2
+4  A: 

1) Having the whole program in a try block will not incur any performance hit, apart from that incurred by having exceptions enabled at all

2) It is OK because you are throwing by value. Throwing by value means that whatever you throw is copied when thrown. So throwing any temporary is perfectly valid because a copy is made.

3) The std::exception class, as far as I can determine, can only ever throw a char*. However you could always subclass it and implement support for wchar if you wanted.

It is worth noting that you shouldn't just have a try catch around main() if that is what you were intending.

radman
+8  A: 

Technically you don't throw the actual object, you throw a copy of it. That's why you can get away with throwing a temporary. Catching a reference also gets a reference to the copy.

This can bite you if you rethrow an exception from within a catch block, you can fall victim to the slicing problem. That's why you don't do:

catch (std::exception & e)
{
    throw e;  // bad, always throws std::exception rather than what was caught
}

But rather

catch (std::exception & e)
{
    throw;  // good, rethrows the exact copy that you caught without making another copy
}

P.S. There's no rule saying you couldn't return a UTF-8 string from what. It would be up to you to convert it to UTF-16 for Windows I/O. The standard exception classes were never explicitly designed or extended for Unicode, nor are any non-standard extensions added just for Windows.

Mark Ransom
actually... at least on MSVC (2005), rethrowing with e.g. `throw e;` works as long as you catched by reference...
smerlin
@smerlin: for Mark's first example, "working" means slicing the exception. If it doesn't do that, it's a non-compliant C++ implementation.
Steve Jessop
@Steve: did another test, and the catch clauses surrounding the rethrow, only catched the exception as a std::exception, but the debugger still showed all information of the original exception. So it seems the compiler is standard compliant, at least in release mode, it slices the exception completely.
smerlin