Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ try catch practices

Is this considered good programming practice in C++:

try {
// some code

}
catch(someException) {
// do something
}
catch (...) 
{

// left empty   <-- Good Practice???
} 
like image 716
Tony The Lion Avatar asked Jun 03 '10 14:06

Tony The Lion


People also ask

Is try catch a good practice?

It's considered best practice to put as little code as possible in each try / catch block. This means that you may need multiple try / catch blocks, instead of just one. The benefits of this are that: it's easy to see which code raises which exceptions (and which code doesn't raise exceptions)

Does Try Catch work in C?

Yes, it is limited to one try-catch in the same function.

Is try catch good practice C++?

This is not good programming practice in C++ or in any other language. Silent failures are bad and will bite you sooner or later. If you are going to catch (...) the very least you should do is log that you are doing it. You may also need to delete some objects if you are not using RAII.

What can I use instead of 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. 5. finally: It is executed after the catch block.


1 Answers

No! That is a terrible practice!

Just about the only time you should catch (...) and not rethrow the exception would be in main() to catch any otherwise unhandled exceptions and to display or log an error before exiting.

If you catch (...), you have absolutely no idea what exception was thrown, and thus you can't know whether it is safe to continue running.

like image 110
James McNellis Avatar answered Oct 07 '22 16:10

James McNellis