Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I guess all the possible exceptions that could be thrown in C++?

Tags:

c++

I am including a third party header file. It has functions that may/may not throw exceptions. In my source code, how do I determine which exceptions could possibly be thrown from that file? It was an interview question. My reply was go through the function declarations and look for exception specification. That could give us some hint. Is there any other way with which we can predict exceptions that could be thrown?

like image 875
DIVAKAR VENKATRAMANI Avatar asked Oct 19 '22 10:10

DIVAKAR VENKATRAMANI


1 Answers

This has several aspects:

  • If exceptions are declared for a function, only those (and derived classes, of course) can possibly be thrown, all others will cause program termination.
  • Even if exceptions are declared for a function, not every compiler actually enforces this rule.
  • If no exceptions (not an empty set of exceptions!) are declared for a function, anything may be thrown.
  • Reasonable code will never throw anything that is not derived from std::exception, so assuming that or a derived type is thrown is a good approach.
  • Good code will document error handling, although you should implicitly expect std::bad_alloc from any function allocating memory.
like image 68
Ulrich Eckhardt Avatar answered Oct 22 '22 00:10

Ulrich Eckhardt