Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging Caught and Uncaught Exceptions?

I have been working with Exceptions lately. I think it makes sense to log uncaught Exceptions, because it greatly helps developers to take care of possible problems in the source by simply looking at Exception log. However, when an exception is dealt with, is there a need to log it any longer? Yes, to some extent. If you have "bad" developers who write code that has bugs, then by simply catching Exceptions will make the bugs go "away". For example:

try
{
 fopen('/path/to/file','w');
}
catch (Exception $e)
{
 // Display an error to user
}

The above code is PHP. The point is, this kind of code, imo, should not exist. Exceptions are meant to be exceptional and occur rarely, but with this code they occur more than rarely. For instance, the developer does not check if the file exists and he does not check if he has permissions to write to it. Instead, it should be:

try
{
 if (file_exists('/path/to/file') && is_writable('/path/to/file'))
  fopen('/path/to/file','w');
 else
  // Display an error to user about file not existing or not being writable
}
catch (Exception $e)
{
 // Display an error to user about an unexpected error
}

This makes pretty much sense now. The exception is thrown and caught only if it is exceptional (e.g. server crash, power outage, whatever). But what if the developer uses Exceptions for everything and the omits checks - is there a way for me to log caught exceptions?

I don't want developers to put everything in try-catch blocks to "solve" issues. I want them to explicitly check whatever they should check - and leave exceptions for exceptional situations like hardware failure, server crash, etc.

like image 673
Tower Avatar asked Jul 04 '09 14:07

Tower


1 Answers

Exceptions are meant to be exceptional and occur rarely, but with this code they occur more than rarely.

I think that's a misconception. The point of exceptions is to separate the ideal flow from the error-handling flow.

like image 137
troelskn Avatar answered Nov 11 '22 00:11

troelskn