Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an occasion where using catch all clause : catch (...) is justified?

Each time I have seen the catch all statement:

try 
{
  // some code 
}
catch (...)
{

}

it has always been an abuse.

The arguments against using cache all clauses are obvious. It will catch anything including OS generated exceptions such as access violations. Since the exception handler can't know what it's dealing with, in most cases the exceptions will manifest as obscure log messages or some incoherent message box.

So catch(...) seems inherently evil.

But it is still implemented in C++ and other languages (Java, C#) implements similar mechanisms. So is there some cases when its usage is justified?

like image 993
Alon Avatar asked Dec 01 '09 09:12

Alon


People also ask

Does try catch catch all exceptions?

We can use try catch block to protect the code. Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.

Should I catch all exceptions Java?

It is bad practice to catch Exception -- it's just too broad, and you may miss something like a NullPointerException in your own code. For most file operations, IOException is the root exception. Better to catch that, instead.


1 Answers

(1) It's not true that the statement will catch OS exceptions. Your use of the term "Access Violation" betrays a Windows background; it was true for older MSVC++ versions.

(2) Regardsless, the catch-all behavior is useful for threads with specific purposes. Catching the failure allows the thread to report it failed. Without it, the other parts of the program need to deal with the possibility of a thread just disappearing. It also allows you to log which thread failed, and the arguments used to start the thread.

like image 74
MSalters Avatar answered Nov 04 '22 16:11

MSalters