Handling Uncaught Exceptions2:54 with Alena Holligan
Sometimes you're unable to catch every exception, but you want to make sure nothing important gets missed. PHP provides a way to handle these exceptions, by setting a default exception handler.
It's best to catch and handle as many exceptions as possible 0:00 as soon as they happen, rather than leaving them to bubble up. 0:04 As it enhances the user experience and 0:08 reduces the likelihood that they will break your application in some way. 0:10 Half writing a file for example. 0:15 However, sometimes exceptions happen when we're not expecting them. 0:17 They are exceptions after all. 0:21 Especially now that we've turned errors into exceptions. 0:24 Once again, PHP provides a way to handle these exceptions, 0:28 by setting a default exception handler. 0:32 Let's go back into Work Spaces and set one up. 0:35 Let's add another expression that will cause an exception. 0:38 Echo 10/0 then let's refresh the browser. 0:41 We no longer see our end of file because this new exception is 0:49 not caught in handled, so execution of the script stops there. 0:52 Let's add the default exception handler. 0:57 Setting up a default exception handler is much like setting up an error handler. 1:03 Use the set, exception, handler. 1:07 And pass in the function you want to use. 1:14 Exception_handler. 1:17 Then we add the new exception_handler function. 1:23 This function needs to accept one parameter, the exception thrown. 1:36 Just like with any other caught exception, 1:40 we can now do any exception handling we want. 1:42 Let's just echo, uncaught exception, 1:45 And then our getMessage. 1:53 Now let's refresh the page. 1:59 This time we see that the exception handler did catch the error. 2:03 But it did not allow the script to continue processing. 2:07 That's how the uncaught exception handler works. 2:10 So it's a good idea to catch exceptions and 2:13 not rely on the default exception handler. 2:15 Make sure you check the notes associated with this video for further resources. 2:18 >> We've covered everything you need to know to get started 2:23 implementing exception handling in your object oriented application. 2:27 Throwing and catching exceptions gives you robust control 2:31 of your application when something goes wrong. 2:34 By turning PHP errors into exceptions 2:37 you improve communication throughout all parts of your application. 2:40 Start using exception handling when accepting data or 2:44 communicating with an external source. 2:48 Until next time. 2:50 Have fun and keep learning. 2:52
You need to sign up for Treehouse in order to download course files.Sign up