Function Definitions and Throw

   20 February 2007, terribly early in the 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.



  1. 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 arbitrarily abort() on you. So no one bothers to use exceptions lists to work around this “feature”.

    [ed. fix typos]

Don't be shy, you can comment too!

Some things to keep in mind: You can style comments using Textile. In particular, *text* will get turned into text and _text_ will get turned into text. You can post a link using the command "linktext":link, so something like "google": will get turned in to google. I may erase off-topic comments, or edit poorly formatted comments; I do this very rarely.