Ensuring that Exceptions are always Caught

By : sachin
Source: Stackoverflow.com
Question!

Exceptions in C++ don't need to be caught (no compile time errors) by the calling function. So it's up to developer's judgment whether to catch it using try/catch (unlike in Java).

Is there a way one can ensure that the exceptions thrown are always caught using try/catch by the calling function?

By : sachin


Answers

There was once an attempt to add dynamic exception specifications to a function's signature, but since the language could not enforce their accuracy, they were later depreciated.

In C++11 and forward, we now have the noexcept specifier.
Again, if the signature is marked to throw, there is still not requriement that it be handled by the caller.


Depending on the context, you can ensure that exceptional behaviour be handled by coding it into the type system.

See: std::optional as part of the library fundamentals.



You shouldn't be using an exception here. This obviously isn't an exceptional case if you need to be expecting it everywhere you use this function!

A better solution would be to get the function to return an instance of something like this. In debug builds (assuming developers exercise code paths they've just written), they'll get an assert if they forget to check whether the operation succeded or not.

class SearchResult
{
  private:
    ResultType result_;
    bool succeeded_;
    bool succeessChecked_;

  public:
    SearchResult(Result& result, bool succeeded)
      : result_(result)
      , succeeded_(succeeded)
      , successChecked_(false)
    {
    }

    ~SearchResult()
    {
      ASSERT(successChecked_);
    }

    ResultType& Result() { return result_; }
    bool Succeeded() { successChecked_ = true; return succeeded_; }
}


Outside the scope of your question so I debated not posting this but in Java there are actually 2 types of exceptions, checked and unchecked. The basic difference is that, much like in c[++], you dont have to catch an unchecked exception.

For a good reference try this

By : shsteimer


This video can help you solving your question :)
By: admin