devxlogo

Exception specifications

Exception specifications

Question:
I recently learned that the C++ draft standard requires that an implementation not perform any static checking on a function’s exception specification (aside from inherited virtual functions and function pointers). This makes the following legal (copied from the standard, sec 15.4 par 10):

extern void f() throw(X, Y);void g() throw(X){    f();  // OK}
Question 1: Why would they do such a thing?

Question 2: Are lint-like tools available that can give warnings about these situations?

It seems to me that without any static checking, the throw specifer is all but useless for a typical project.

Answer:
Yes, you heard correctly. Static checking of exception specifications can bevery tedious and time-consuming for the compiler. Consider the following:

struct X {};struct Y {};void foo () throw (Y);void bar () throw (Y);void off () throw (X,Y);void foo (){   bar ();}void bar (){   off ();}
The compiler would never know while compiling foo that there is a possibility the function bar may throw a X exception. The compiler cannot check for this unless it follows the call trace until the point of origin for each and every function that is called from foo.Also consider:
void throwsExceptions () throw (…);bool neverThrows () throw (){   try   {	throwsExceptions ();   }   catch(…)   {      return false;   }   return true;}
See the point? Not allowing the call to throwsExceptions in the above codewould make it impossible to write such exception-safe functions altogether.

I hope I have convinced you!

I’m afraid I cannot help you with the lint question, because I have never used one and am not aware if there are products that do such checking.

See also  Why ChatGPT Is So Important Today

Your comment that exception specifications don’t have much use is true toan extent. You see, it is very difficult to cope with changes toheader files during development, and the specifications on exceptionstend to keep growing. I know at least one author who advises the avoidance of exceptions. My rule of thumb has always beento specify exceptions thrown only in cases where the class in questionbelongs to a reuseable library. In other words, if the function has a lotof clients, I specify exceptions; otherwise, I don’t.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist