This node used to live under C++: catch is exempt from standard C++ syntax, until an editor and I agreed to move it to this title -- after all, the syntax of catch is standard, seeing as ISO C++ defines it that way.

Look carefully at this code. See anything wrong?

struct TooBig {
  int val;                       // Too big value
  TooBig(int val_) : val(val_) {}
};

void g()
{
  int x = function1(17);       // Get some value
  if (x > 29)
    throw TooBig(x);

  try {                   
    int y = function_throwing_TooBig(x);
    std::cout << "Got the value " << y << endl;
  }
  catch (TooBig z)
    std::cerr << "Oops! " << z.val << " is too big!" << endl;
}
Seems straightforward enough (if you can consider any C++ code using exceptions "straightforward").

Unfortunately, it's not legal (ISO) C++. While

  if (condition)
    do_something();
is legal syntax, the seemingly equivalent
  try {
    // ...
  }
  catch (X x)
    do_something(x);
is NOT! You have to wrap the body of catch and try in brackets, even if it's just a single statement.

This is supposed to be "clearer". After all, lots of people insist on surrounding every single-statement if or else or for or while with braces, "because it's clearer and my lousy excuse for a text editor can't handle indentation." These people would be better served eating quiche and programming in Pascal, but let's accommodate them. Now, obviously we can't change existing syntax. But we can invent new syntax for new keywords, and make that inconsistent with the old syntax! That way, C programmers can't program exceptions (because the new syntax is inconsistent with what they know), and Pascal programmers can't read control flow (because the old syntax is different from that for exceptions).

Maybe that's why They call them EXCEPTIONS...

Log in or registerto write something here or to contact authors.