-1

There are many discussions why catching the top-level exception is a bad practice. However, sometimes the developer does not care about if the operation fails.

For example, there is a method which initializes variables based on a file but the variables already have valid values. The developer might not care why the reading failed.

In this case, catching general exception could be valid (could be?), except the system exceptions (no memory, io error etc.). Would be this then a valid pattern?

(Note that example has been updated based on @stuard comment.)

operation()

try
{
    operation_which_can_fail()
}
catch (Exception ex)
{
    if (ex is SystemException)
    {
        throw;
    }
    // Do not care about any other error
    // Do some log maybe
}

next_operation()

What would be the expected solution which does not overwhelm the developer by handling all potential exceptions but also satifies the general error handling principles (only catch errors that you handle)?

Tibor Takács
  • 3,535
  • 1
  • 20
  • 23

1 Answers1

1

If user doesn't care about file reading outcome, then you should catch IOException, not Exception which swallows errors user should care about:

try {
  operation_which_can_fail(); 
}
catch (IOException) {
  // We don't care about files, reading, permissions etc. 
  // Since "...variables already have valid values..." we can ignore the problem
}      
catch (Exception) {
  // Write some log : we have some unexpected problem
  ...     
  // rethrow exception : we don't want to swallow unknown problem warning  
  throw;  
} 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • This can be a solution for sure, however, the developer has to know about `IOException`. But what about `NullReferenceException`? Or any other non-system exception? My goal would be to avoid the normal exception handling logic (which I apply in most of the cases) but handling the highest level error. But it might be that the answer is that it is not possible to do so. – Tibor Takács Sep 09 '20 at 20:48