Re: Exception misinformation

From: Date: Tue, 06 Jul 2004 22:02:42 +0000
Subject: Re: Exception misinformation
References: 1 2 3  Groups: php.pear.dev 
Request: Send a blank email to pear-dev+get-31677@lists.php.net to get a copy of this message
On Tue, 06 Jul 2004 22:44:19 +0100, Sergio Carvalho <sergio.carvalho@portugalmail.com> wrote: > 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). > Ugly, but doable It would make more sense to put these in nested if/else blocks. You could also do nested try/catch, but that makes things even harder to read. I suppose it's no worse than the if/else stuff.... I still wonder about this, though, as many experienced coders say that Exceptions shouldn't be used for code flow handling. -- DB_DataObject_FormBuilder - The database at your fingertips http://pear.php.net/package/DB_DataObject_FormBuilder paperCrane --Justin Patrin--

« previous php.pear.dev (#31677) next »