Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensuring that Exceptions are always caught

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?

like image 722
sachin Avatar asked Aug 04 '08 10:08

sachin


People also ask

Where should exceptions be caught?

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.

Which statement is used to catch all types of exceptions?

Catch block is used to catch all types of exception.

What happens if you don't catch exceptions?

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.

How do you handle exceptions in Java without try catch?

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.


2 Answers

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.

like image 156
Chris Jester-Young Avatar answered Oct 02 '22 23:10

Chris Jester-Young


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_; } } 
like image 40
Scott Langham Avatar answered Oct 03 '22 00:10

Scott Langham