Function Definitions and Throw
20 February 2007, early morning
Today while reading about auto_ptr’s — a topic for another day — I saw the function declaration/definition ~auto_ptr() throw() { delete ptr; }
. I thought to myself, “What the hell is that throw() all about?” C++ can be a strange and esoteric language. Keywords get reused often, and mean different things depending on their context. Clearly this had something to do with exceptions, but what? After looking in my giant tome of C++ knowledge I had an answer. In C++ you can be explicit about what exceptions a function may throw. You do this by listing the exceptions within the parentheses following the throw
keyword, which you include after the functions name. I have very vague memories of this being discussed in CS 246, though I can’t be certain it was. Anyway, I took CS 246 a bajillion years ago. throw()
corresponds to a guarantee the function throws no exceptions. If you don’t include the throw
keyword when declaring a function, then the function can throw any exceptions. In Java this is actually required behaviour: if your function throws an exception, you must list the exceptions thrown using the throws
keyword. I haven’t had to program in Java in ages.
C++ exception lists are messed up, so no one used them.
If your program throws an exception that’s not in the list specified by it’s method signature then it calls
abort()
(which isn’t very nice behaviour for more systems). And the compiler doesn’t bother to enforce that you adhere to the exception list at compile time, so there’s no way to know if you program is going to arbitrarilyabort()
on you. So no one bothers to use exceptions lists to work around this “featureâ€.[ed. fix typos]
by Ryan on February 20 2007, 11:51 pm #