Ensuring that Exceptions are always caught
Asked Answered
C

7

31

Exceptions in C++ don't need to be caught (no compile time errors) by the calling function. So it's up to the developer's judgment whether to catch them 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?

Cupreous answered 4/8, 2008 at 10:1 Comment(2)
The consensus on Java's procrustean approach to exception specifications is that it's badly broken.Chloral
Bruh I was 6 years old when this question was asked.Westney
C
27

No.

See A Pragmatic Look at Exception Specifications for reasons why not.

The only way you can "help" this is to document the exceptions your function can throw, say as a comment in the header file declaring it. This is not enforced by the compiler or anything. Use code reviews for that purpose.

Convoy answered 4/8, 2008 at 10:10 Comment(0)
H
10

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_; }
}
Hausfrau answered 24/9, 2008 at 9:24 Comment(6)
+1 to that. If you expect some result, it shouldn't be returned in form of an exception.Ultun
GCC at least has a function attribute to require handling the return value. Less messy than this extra bool.Virchow
Show me an example of someone who isn't a quack or a hack saying that exceptions are only for exceptional situations.Deyo
@JohnDibling I've heard this a lot from fellow Java developers, but I've yet to hear/see those exact words from any books, references or notable developers. If so, then the Python creator(s) didn't get the memo :)Victorinavictorine
@JohnDibling Show me someone who's serious who doesn't say it.Voussoir
This class is missing a copy constructor and an assignment operator. The copy constructor is very important, since values are returned by copy (which may be elided). In C++11, you probably want a move constructor, rather than a copy constructor, since you want to reset successChecked in the object being copied.Voussoir
B
4

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

Brittnee answered 4/8, 2008 at 17:51 Comment(0)
S
2

Chris' probably has the best pure answer to the question:

However, I'm curious about the root of the question. If the user should always wrap the call in a try/catch block, should the user-called function really be throwing exceptions in the first place?

This is a difficult question to answer without more context regarding the code-base in question. Shooting from the hip, I think the best answer here is to wrap the function up such that the recommended (if not only, depending on the overall exception style of the code) public interface does the try/catch for the user. If you're just trying to ensure that there are no unhandled exceptions in your code, unit tests and code review are probably the best solution.

Schoonover answered 5/8, 2008 at 4:56 Comment(0)
A
1

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.

Array answered 8/5, 2016 at 15:7 Comment(0)
F
0

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

I find it rather funny, that the Java crowd - including myself - is trying to avoid checked Exceptions. They are trying to work their way around being forced to catch Exceptions by using RuntimeExceptions.

Frodi answered 4/8, 2008 at 18:14 Comment(0)
C
-1

Or you could start throwing critical exceptions. Surely, an access violation exception will catch your users' attention.

Cowry answered 4/8, 2008 at 17:33 Comment(2)
What, praytell, is a "critical" exception?Deyo
If you had read past the period, you might have noticed that I explicitly mentioned one.Cowry

© 2022 - 2024 — McMap. All rights reserved.