Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Jun 6, 1997

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 be very 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 code would 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.

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

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date