Catch as catch can

A light-hearted look at exception handling


When should you raise an exception?

Glad you asked me that.

You should only raise an exception when you have encountered a truly exceptional situation. You should not raise an exception in a mildly-surprising-for-the-time-of-year kind of situation, and you certainly mustn’t raise an exception on a whim.

For example, if your routine threw because part of the GUID number you have just generated reads ‘SHELLOIL’ if you look at it upside down, this would be a Bad Thing. So please don’t.

As for using exceptions as a spectacular alternative to the much-maligned goto: this is the sort of behind-the-bikesheds activity in which Reg readers would never indulge.

Exception specifications

A quick reminder; exception specifications are extra bits glued onto function definitions that look like this:

int foo() throw(excpt1, excpt2); // can throw excpt1 and excpt2
int moo() throw(nothing);        // can throw nothing
int poo() throw();               // can't throw nothing. Umm...
int coo();                       // can't never not throw nothing

So that’s clear.

Exception specifications divide the C++ world into three rival and irreconcilable schools of thought:

  • There are those who have never heard of them. This faction doesn’t use exception specifications in its code.
  • There are those who have heard of them, but can’t be bothered to put them in. After all, we already gave in on the const thing with parameters, and that’s caused no end of trouble. This faction doesn’t use exception specifications in its code.
  • There are those clever clogs who have actually looked into the matter and given it some thought. These persons have discovered that they aren’t, in fact, any cop. This faction doesn’t use exception specifications in its code.

Until these three groups bury the hatchet and settle their differences, I can see no long-term future for C++.

Meanwhile, Java has a version of exception specifications called “checked exceptions” which are possibly even worse.

What to do if you get an exception

Faced with this question, some writers indulge in hand waving. Fortunately I am able to offer specific guidelines, based on standard practice as observed in commercial software, and some informed guesswork.

  • If you are running as some sort of web service, the standard approach on handling an exception is to send the user a page of ODBC diagnostics, preferably mashed up with a few suggestions from Apache.

    But this approach doesn’t just work with HTML output. For example some banks have also adopted it, as a novel method of telling you that you aren’t going to see your card back from the ATM any time soon.

  • If you are running as a background process with no user interaction, don’t just disappear silently. Be sure to do a memory dump, so gifting the user a digital turd — a binary lump of disk space of no use to man or beast. Naturally it won’t help you-the-programmer find the cause of the exception, because even if the user troubles to send it to you, like everyone else you don’t keep your debug symbol tables in version control, kidding yourself that you can rebuild them identically from the source.

    (By the way, the Windows API call to create this thing, MiniDumpWriteDump(), is one of my faves: as it says in the docs, sometimes you have to throw another exception to get it to fire. Neat.)

  • If you are running as a GUI program, now’s the time to pop up a modal message box. It doesn’t really matter what text you put in it, because the user will ignore it.

    A refinement, especially popular with Delphi programmers, is to put up further, identical message boxes at a one half second interval, so that unless the user intervenes and starts closing them at a greater rate, the whole system will eventually die from memory exhaustion.

  • If you’re running under Windows XP, consider converting the exception into a null pointer dereference in the catch handler:

    catch(...) { // now we're really stuffed
        int * p = 0;
        *p = 22;
    }
    

    This has the advantage over an ordinary crash that you will get one of those special OS-supplied dialogs, that asks permission to send log details back to Microsoft. Naïve users will interpret this as a Windows fault, and will direct their bile Redmondwards.

Of course, all the above techniques can be combined in fresh and original ways. Never be afraid to experiment.

The primary duty of an exception handler is to get the error out of the lap of the programmer and into the surprised face of the user. Provided you keep this cardinal rule in mind, you can’t go far wrong. ®


Other stories you might like

  • Firefox kills another tracking cookie workaround
    URL query parameters won't work in version 102 of Mozilla's browser

    Firefox has been fighting the war on browser cookies for years, but its latest privacy feature goes well beyond mere cookie tracking to stop URL query parameters.

    HTML query parameters are the jumbled characters that appear after question marks in web addresses, like website.com/homepage?fs34sa3aso12knm. Sites such as Facebook and HubSpot use them to track users when links are clicked, and other websites like YouTube use them to enable certain site features too.

    On June 28, Firefox 102 released a feature that enables the browser to "mitigate query parameter tracking when navigating sites in ETP strict mode." ETP, or enhanced tracking protection, encompasses a variety of Firefox components that block social media trackers, cross-site tracking cookies, fingerprinting and cryptominers "without breaking site functionality," says Mozilla's ETP support page.

    Continue reading
  • Old school editor Vim hits version 9 with faster scripting language
    All of the famed user-friendliness and ease of use, but 'drastically' better performance

    Old school editor fans, rejoice: some two and a half years after version 8.2, Vim 9 is here with a much faster scripting language.

    Vim 9 has only a single big new feature: a new scripting language, Vim9script. The goal is to "drastically" improve the performance of Vim scripts, while also bringing the scripting language more into line with widely used languages such as JavaScript, TypeScript, and Java.

    The existing scripting language, Vimscript, remains and will still work. Only scripts beginning with the line vim9script will be handled differently. The syntax changes are relatively modest; the important differences are in things like local versus global variables and functions, and that functions defined with :def will be compiled before they are run. This allows many errors to be caught in advance, but more significantly, compiled functions execute from 10× to 1000× faster.

    Continue reading
  • Iceotope: No need to switch servers to swap air-cooled for liquid-cooled
    Standard datacenter kit just needs a few tweaks, like pulling off the fans

    Liquid cooling specialist Iceotope claims its latest system allows customers to easily convert existing air-cooled servers to use its liquid cooling with just a few minor modifications.

    Iceotope’s Ku:l Data Center chassis-level cooling technology has been developed in partnership with Intel and HPE, the company said, when it debuted the tech this week at HPE’s Discover 2022 conference in Las Vegas. The companies claim it delivers energy savings and a boost in performance.

    According to Iceotope, the sealed liquid-cooled chassis enclosure used with Ku:l Data Center allows users to convert off-the-shelf air-cooled servers to liquid-cooled systems with a few small modifications, such as removing the fans.

    Continue reading
  • Gartner predicts 9.5% drop in PC shipments
    Stark contrast to 11 percent increase year-over-year in 2021 shipments

    The party is over for PC makers as figures from Gartner suggest the market is on course for a breathtaking decline this year.

    According to the analysts, worldwide PC shipments will decline by 9.5 percent, with consumer demand leading the way – a 13.5 percent drop is forecast, far greater than business PC demand, which is expected to drop by 7.2 percent year on year.

    The PC market in the EMEA region is forecast to fare even worse, with a 14 percent decline on the cards for 2022. Gartner pointed the finger of blame at uncertainty caused by conflicts, price increases and simple unavailability of products. Lockdowns in China were also blamed for an impact in consumer demand.

    Continue reading

Biting the hand that feeds IT © 1998–2022