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 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?
You should catch the exception when you are in the method that knows what to do. For example, forget about how it actually works for the moment, let's say you are writing a library for opening and reading files. Here, the programmer knows what to do, so they catch the exception and handle it.
Catch block is used to catch all types of exception.
What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console. The message typically includes: name of exception type.
throws: The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.
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.
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_; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With