Recover from caught exception


I was wondering if there was a way to recover from an exception, in the sense that I can continue.

$file = null;

try {
  $file = new File('bar.txt'); // dummy class
catch(Exception $e) {
  //file wasn't found so create it
  $file->createFile(); //try again

I’m using a File class as an example but I’m asking the question in a more of a general view of any caught exception.


This old thread meanders a bit, but might be interesting to you, its one I leaned a lot from.

In that example it seems you are using exceptions to fork the code, which is not what they are for. But lets skip that.

In my book, it may depend upon whom you are writing the exception for a fellow developer or (yourself) or a user (member of the public).

If you want to continue on another path one which is not expected - but might happen - and its for the dev person, then I’d tend to go on and write a custom exception and bundle it along with the class.

Uppermost in your programme you can also set an exception handler which spits out a load of debug when it detects one setting, or a nicer apology when it detects its on your live server, for example.