Skip to content

[recipes] Bad exception-catching pattern

The new recipes use the exception-catching pattern

int main(int argc, char** argv)
{
  try{
    //...
  }
  catch (Dune::Exception &e){
    std::cerr << "Dune reported error: " << e << std::endl;
    return 1;
  }
  catch (...){
    std::cerr << "Unknown exception thrown!" << std::endl;
    return 1;
  }
}

Although this is common in programs based on Dune, we should avoid teaching this. It turns at least standard exceptions into a useless error message. And under certain circumstances the standard library would already print much more useful error messages for exceptions that leave main(), including Dune exceptions, because these are derived from std::exception these days. And if something not derived from std::exception throws out of main, at least the name of the type will be printed.

Alternatives:

  • Don't handle any exception. Has the drawback that the standard library produces useful error messages only under certain circumstances (debug libraries being installed I think, but I'm not sure). Has the advantage that it concentrates on the core of these educational examples, and leaves out distracting side-questions.
  • Handle std::exception: A useful error message can be produced for most exceptions, including Dune exceptions, and Dune::className(e) can be used to print the precise dynamic type of the exception.
  • Handle std::exception and Dune::Exception. You can avoid printing the type of the exception twice, because Dune exceptions tend to already include it in their message. But that is poorly specified, plus it makes these educational examples more complicated than they need to be.
  • Handle only Dune::Exception: similar to handling just std::exception, but you leave the standard exceptions to be reported by the standard library. Really no advantage over just handling std::exception.