Re: Exception misinformation

From: Date: Tue, 06 Jul 2004 21:44:19 +0000
Subject: Re: Exception misinformation
References: 1 2  Groups: php.pear.dev 
Request: Send a blank email to pear-dev+get-31676@lists.php.net to get a copy of this message
Justin Patrin wrote:
This is a point that *must* be talked about. Especially "using exceptions as flow control". What does this mean exactly? Let's say that a package throws a file not found exception. Perhaps I want to try another file (or group of files), meaning a loop in the code based on whether an exception is caught. This is pretty ugly. But the file not found exception is an error and therefore an exception for the class I'm calling. Or say that if a file isn't found, I want to switch to an alternate method of getting the information I need? If file not found is too easy to get around for you (file_exists), then consider trying to connect to an FTP server. If it fails, use a file on the filesystem, or possibly us eanother method. If the FTP class throws an exception, I'm forced to use that exception to change the flow of my code. There is simply no way of getting around that. How can this be resolved? I don't see any good way. If we use Exceptions for Errors, some people will be forced to use them for this kind of flow handling.
If the recovery logic is small, I usually handle it right in the catch block. If it is longer, or there's a cascade of alternatives, I prefer the following logic: try { // Get data via FTP } catch (Exception e) { // Cleanup remnants of FTP attempt } if (!isDataHere()) {
    try {
          // Get data via HTTP
    } catch (Exception e) {
       // Cleanup remnants of HTTP attempt
    }
} if (!isDataHere()) {
    try {
          // Get data via some other method
    } catch (Exception e) {
       // Cleanup remnants of attempt
       throw new SomeException('Unable to retrieve data', e);
    }
} This is the kind of stuff that should be in coding guidelines, even if non-mandatory (recomendations). Cheers, Sérgio Carvalho

Attachment: [application/pgp-signature] OpenPGP digital signature signature.asc
« previous php.pear.dev (#31676) next »