KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I've been wondering why would I use Exceptions in my PHP. Let's take a look at a simple example: class Worker { public function goToWork() { return $isInThatMood ? // Okay, I'll do it. true : // In your dreams... false; } } $worker = new Worker; if (!$worker->goToWork()) { if (date('l',time()) == 'Sunday') echo "Fine, you don't have to work on Sundays..."; else echo "Get your a** back to work!"; } else echo "Good."; Is there a reason for me to use Exceptions for that kind of code? Why? How would the code be built? And what about code that may produce errors: class FileOutputter { public function outputFile($file) { if (!file_exists($file)) return false; return file_get_contents($file); } } Why would I use Exceptions in the above case? I have a feeling that Exceptions help you to recognize the type of the problem, which occured, true? So, am I using Exceptions appropriately in this code: class FileOutputter { public function outputFile($file) { if (!file_exists($file)) return throw new Exception("File not found.",123); try { $contents = file_get_contents($file); } catch (Exception $e) { return $e; } return $contents; } } Or is that poor? Now the underlying code can do this: $fo = new FileOutputter; try { $fo->outputFile("File.extension"); } catch (Exception $e) { // Something happened, we could either display the error/problem directly echo $e->getMessage(); // Or use the info to make alternative execution flows if ($e->getCode() == 123) // The one we specified earlier // Do something else now, create "an exception" } Or am I completely lost here?
Tags (comma-separated)
Save Edits
Cancel