Error Handling
Introduction <ul><li>How to write an error handler. </li></ul><ul><li>Normally, it displays a message indicating the cause...
<ul><li>There are 3 basic types of runtime errors in PHP:  </li></ul><ul><ul><li>Notices : These are trivial, non-critical...
<ul><li>It should be noted that a syntax error in a PHP script – (EG: missing brace or semi-colon) is treated as a fatal e...
Early Warning <ul><li>Example 1 </li></ul><ul><ul><li>we get a non-fatal error (E_WARNING) </li></ul></ul><ul><ul><li>it s...
Example 1 <ul><li>< ?php </li></ul><ul><li>// initialize the $string variable </li></ul><ul><li>$string =  'a string'; </l...
Example 2 <ul><li>< ?php </li></ul><ul><li>// call a non-existent function </li></ul><ul><li>// this will generate a fatal...
<ul><li>Example 3 </li></ul><ul><ul><li>control which errors are displayed to the user (built-in PHP function called error...
Example 3 <ul><li>< ?php </li></ul><ul><li>// report only fatal errors </li></ul><ul><li>error_reporting (E_ERROR); </li><...
Example 4 <ul><li>< ?php </li></ul><ul><li>// report no fatal errors </li></ul><ul><li>error_reporting (~E_ERROR); </li></...
<ul><li>Although the script above will not display a visible error message, script execution will still stop at the point ...
Rolling Your Own   <ul><li>Changing the way errors are handled.  </li></ul><ul><li>Function called set_error_handler(), it...
<ul><li>Example 5 </li></ul><ul><li>The set_error_handler() function tells the script that all errors are to be routed to ...
Example 5 <ul><li>< ?php </li></ul><ul><li>// define a custom error handler </li></ul><ul><li>set_error_handler ( 'oops' )...
<ul><li>// custom error handler </li></ul><ul><li>function   oops($type, $msg, $file, $line, $context)  { </li></ul><ul><l...
<ul><li>An error occurred while executing this script. Please contact the  webmaster  to report this error.Here is the inf...
<ul><li>Example 6 </li></ul><ul><li>Can use this custom error handler to alter the error message the user sees, on the bas...
Example 6 <ul><li>< ?php </li></ul><ul><li>// define a custom error handler </li></ul><ul><li>set_error_handler ( 'oops' )...
<ul><li>// warnings </li></ul><ul><li>case  E_WARNING: </li></ul><ul><li>// report error </li></ul><ul><li>print   &quot;N...
Pulling the Trigger <ul><li>PHP allows you to use its built-in error handling system to raise your own custom errors as we...
Example(triggerror6.php): <ul><li>< ?php   </li></ul><ul><li>// function to test a number  </li></ul><ul><li>// generates ...
Pulling the Trigger (cont..) <ul><li>The next example rewrites the previous script to use a user-defined error handler to ...
Example(triggererror7.php): <ul><li>< ?php   </li></ul><ul><li>// function to test a number  </li></ul><ul><li>// generate...
<ul><li>// fatals   </li></ul><ul><li>case  E_USER_ERROR:  </li></ul><ul><li>// report error and die()   </li></ul><ul><li...
Catching up <ul><li>In the exception-based approach, program code is wrapped in a try() block, and exceptions generated by...
Catching up (cont..) <ul><li>The exceptions themselves are generated via PHP's throw statement.  </li></ul><ul><li>The thr...
<ul><li>< ?php   </li></ul><ul><li>// PHP 5   </li></ul><ul><li>error_reporting ( 0 );  </li></ul><ul><li>// try this code...
Catching up (cont..) <ul><li>If the file doesn't exist or is unreadable, the throw statement will generate an exception (b...
Example (tryncatcherror9.php) <ul><li>< ?php   // PHP 5   error_reporting (0);  // try this code  try   {       $file  =  ...
Catching up (cont..) <ul><li>When you run this script, you'll see that the message generated by the exception handler cont...
Adding Some Class <ul><li>You can handle different exceptions in different ways, by sub-classing the generic Exception obj...
Example (classerror10.php) <ul><li>< ?php </li></ul><ul><li>// PHP 5 </li></ul><ul><li>// sub-class the Exception class </...
<ul><li>// try this code </li></ul><ul><li>try   { </li></ul><ul><li>testNumber (- 19 ) ; </li></ul><ul><li>} </li></ul><u...
<ul><li>Here's another example, this one illustrating a more useful application - using the exception model in a user auth...
Example (classerror11.php) <ul><li>< ?php   </li></ul><ul><li>// PHP 5  </li></ul><ul><li>// class definition  </li></ul><...
<ul><li>// check that the file is readable   </li></ul><ul><li>if  ( !is_readable ( $this->passwdFile )) {  </li></ul><ul>...
<ul><li>// subclass exceptions   </li></ul><ul><li>class  FileException  extends  Exception  {} ;  </li></ul><ul><li>class...
Upcoming SlideShare
Loading in...5
×

Php Error Handling

4,553

Published on

Published in: Technology
2 Comments
2 Likes
Statistics
Notes
No Downloads
Views
Total Views
4,553
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
137
Comments
2
Likes
2
Embeds 0
No embeds

No notes for slide

Php Error Handling

  1. 1. Error Handling
  2. 2. Introduction <ul><li>How to write an error handler. </li></ul><ul><li>Normally, it displays a message indicating the cause of the error and may also terminate script execution when a PHP script encounters an error. </li></ul><ul><li>Now, while this behaviour is acceptable during the development phase, it cannot continue once a PHP application has been released to actual users. </li></ul><ul><li>In &quot;live&quot; situations, it is unprofessional to display cryptic error messages (which are usually incomprehensible to non-technical users). </li></ul><ul><li>It is more professional to intercept these errors and either resolve them (if resolution is possible), or notify the user with an easily-understood error message (if not). </li></ul>
  3. 3. <ul><li>There are 3 basic types of runtime errors in PHP: </li></ul><ul><ul><li>Notices : These are trivial, non-critical errors that PHP encounters while executing a script. By default, such errors are not displayed to the user at all – we can change this default behaviour. </li></ul></ul><ul><ul><li>Warnings : These are more serious errors - for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination. </li></ul></ul><ul><ul><li>Fatal errors : These are critical errors - for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP's default behaviour is to display them to the user when they take place. </li></ul></ul>
  4. 4. <ul><li>It should be noted that a syntax error in a PHP script – (EG: missing brace or semi-colon) is treated as a fatal error and results in script termination (stop execution). </li></ul><ul><li>PHP errors can be generated by: </li></ul><ul><ul><li>Zend engine </li></ul></ul><ul><ul><li>PHP built-in functions </li></ul></ul><ul><ul><li>user-defined functions </li></ul></ul><ul><li>They may occur at startup, at parse-time, at compile-time or at run-time. </li></ul><ul><li>During the debug phase: </li></ul><ul><ul><li>Use E_ALL type to see all fatal and non-fatal errors generated by our script. </li></ul></ul><ul><ul><li>Use the new E_STRICT error type to view errors that affect the forward compatibility of our code in PHP 5. </li></ul></ul>
  5. 5. Early Warning <ul><li>Example 1 </li></ul><ul><ul><li>we get a non-fatal error (E_WARNING) </li></ul></ul><ul><ul><li>it still get executed but with non-fatal error </li></ul></ul><ul><li>Example 2 </li></ul><ul><ul><li>it call non-existent function </li></ul></ul><ul><ul><li>generate a fatal error </li></ul></ul><ul><ul><li>immediately stops script execution </li></ul></ul>
  6. 6. Example 1 <ul><li>< ?php </li></ul><ul><li>// initialize the $string variable </li></ul><ul><li>$string = 'a string'; </li></ul><ul><li>// explode() a string </li></ul><ul><li>// this will generate a warning or E_WARNING because the number of arguments to explode() is incorrect </li></ul><ul><li>explode ($string); </li></ul><ul><li>? > </li></ul><ul><li>Output </li></ul><ul><li>Warning : Wrong parameter count for explode() in C:wampwww est2part12eg1.php on line 8 </li></ul>
  7. 7. Example 2 <ul><li>< ?php </li></ul><ul><li>// call a non-existent function </li></ul><ul><li>// this will generate a fatal error (E_ERROR) </li></ul><ul><li>callMeJoe () ; </li></ul><ul><li>? > </li></ul><ul><li>Output </li></ul><ul><li>Fatal error : Call to undefined function callMeJoe() in C:wampwww est2part12eg2.php on line 5 </li></ul>
  8. 8. <ul><li>Example 3 </li></ul><ul><ul><li>control which errors are displayed to the user (built-in PHP function called error_reporting()) </li></ul></ul><ul><ul><li>this function tells the script to report only errors that match that type </li></ul></ul><ul><ul><li>&quot;hide&quot; non-fatal errors </li></ul></ul><ul><li>Example 4 </li></ul><ul><ul><li>Use a similar technique to turn off the display of fatal errors </li></ul></ul>
  9. 9. Example 3 <ul><li>< ?php </li></ul><ul><li>// report only fatal errors </li></ul><ul><li>error_reporting (E_ERROR); </li></ul><ul><li>// initialize the $string variable </li></ul><ul><li>$string = 'string'; </li></ul><ul><li>// attempt to explode() a string </li></ul><ul><li>// this will not generate a warning because only fatal errors are reported </li></ul><ul><li>explode ($string); </li></ul><ul><li>? > </li></ul><ul><li>Output </li></ul><ul><li>No output </li></ul>
  10. 10. Example 4 <ul><li>< ?php </li></ul><ul><li>// report no fatal errors </li></ul><ul><li>error_reporting (~E_ERROR); </li></ul><ul><li>// call a non-existent function </li></ul><ul><li>callMeJoe(); </li></ul><ul><li>? > </li></ul><ul><li>Output </li></ul><ul><li>No output </li></ul>
  11. 11. <ul><li>Although the script above will not display a visible error message, script execution will still stop at the point of error and statements subsequent to that point will not be executed. </li></ul><ul><li>error_reporting() gives you control over which errors are displayed; it doesn't prevent the errors themselves. </li></ul>
  12. 12. Rolling Your Own <ul><li>Changing the way errors are handled. </li></ul><ul><li>Function called set_error_handler(), it allows to divert all PHP errors to a custom function that are defined, instead of sending them to the default handler. </li></ul><ul><li>This custom function must be capable of accepting a minimum of two mandatory arguments: </li></ul><ul><ul><li>error type </li></ul></ul><ul><ul><li>corresponding descriptive message </li></ul></ul><ul><li>and up to three additional arguments </li></ul><ul><ul><li>the file name </li></ul></ul><ul><ul><li>line number where the error occurred </li></ul></ul><ul><ul><li>dump of the variable space at the time of error </li></ul></ul>
  13. 13. <ul><li>Example 5 </li></ul><ul><li>The set_error_handler() function tells the script that all errors are to be routed to my user-defined oops() function </li></ul><ul><li>This function is set up to accept five arguments:- </li></ul><ul><ul><li>error type </li></ul></ul><ul><ul><li>message </li></ul></ul><ul><ul><li>file name </li></ul></ul><ul><ul><li>line number </li></ul></ul><ul><ul><li>context </li></ul></ul><ul><li>These arguments are then used to create an error page that is friendlier and more informative than PHP's standard one-line error message </li></ul>
  14. 14. Example 5 <ul><li>< ?php </li></ul><ul><li>// define a custom error handler </li></ul><ul><li>set_error_handler ( 'oops' ); </li></ul><ul><li>// initialize the $string variable </li></ul><ul><li>$string = 'a string' ; </li></ul><ul><li>// explode() a string </li></ul><ul><li>// this will generate a warning because the number of arguments to explode() is incorrect </li></ul><ul><li>// the error will be caught by the custom error handler </li></ul><ul><li>explode ($string); </li></ul>
  15. 15. <ul><li>// custom error handler </li></ul><ul><li>function oops($type, $msg, $file, $line, $context) { </li></ul><ul><li>echo &quot;<h1>Error!</h1>&quot;; </li></ul><ul><li>echo &quot;An error occurred while executing this script. Please contact the <a href=mailto:webmaster@somedomain.com>webmaster</a> to report this error.&quot;; </li></ul><ul><li>echo &quot;<p />&quot;; </li></ul><ul><li>echo &quot;Here is the information provided by the script:&quot;; </li></ul><ul><li>echo &quot;<hr><pre>&quot;; </li></ul><ul><li>echo &quot;Error code: $type<br />&quot;; </li></ul><ul><li>echo &quot;Error message: $msg<br />&quot;; </li></ul><ul><li>echo &quot;Script name and line number of error: $file:$line<br />&quot;; </li></ul><ul><li>$variable_state = array_pop ($context); </li></ul><ul><li>echo &quot;Variable state when error occurred: &quot;; </li></ul><ul><li>print_r ($variable_state); </li></ul><ul><li>echo &quot;</pre><hr>&quot;; </li></ul><ul><li>} </li></ul><ul><li>?> </li></ul><ul><li>Output </li></ul><ul><li>Error! </li></ul>
  16. 16. <ul><li>An error occurred while executing this script. Please contact the webmaster to report this error.Here is the information provided by the script: </li></ul><ul><li>Error code: 2 Error message: Wrong parameter count for explode() Script name and line number of error: C:wampwww est2part12eg5.php:12 Variable state when error occurred: a string </li></ul>
  17. 17. <ul><li>Example 6 </li></ul><ul><li>Can use this custom error handler to alter the error message the user sees, on the basis of the error type </li></ul><ul><li>Note that certain error types can't be handled in this way. </li></ul><ul><li>For example, a fatal E_ERROR will prevent the PHP script from continuing. </li></ul><ul><li>So, it can never reach a user-created error-handling mechanism. </li></ul>
  18. 18. Example 6 <ul><li>< ?php </li></ul><ul><li>// define a custom error handler </li></ul><ul><li>set_error_handler ( 'oops' ); </li></ul><ul><li>// initialize $string variable </li></ul><ul><li>$string = 'a string' ; </li></ul><ul><li>// this will generate a warning </li></ul><ul><li>explode ($string); </li></ul><ul><li>// custom error handler </li></ul><ul><li>function oops($type, $msg, $file, $line, $context) { </li></ul><ul><li>switch ($type) { </li></ul><ul><li>// notices </li></ul><ul><li>case E_NOTICE: </li></ul><ul><li>// do nothing </li></ul><ul><li>break; </li></ul>
  19. 19. <ul><li>// warnings </li></ul><ul><li>case E_WARNING: </li></ul><ul><li>// report error </li></ul><ul><li>print &quot;Non-fatal error on line $line of $file: $msg <br />“; </li></ul><ul><li>break; </li></ul><ul><li>// other </li></ul><ul><li>default: </li></ul><ul><li>print &quot;Error of type $type on line $line of $file: $msg <br />&quot;; </li></ul><ul><li>break; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>?> </li></ul><ul><li>Output </li></ul><ul><li>Non-fatal error on line 10 of C:wampwww est2part12eg6.php: Wrong parameter count for explode() </li></ul>
  20. 20. Pulling the Trigger <ul><li>PHP allows you to use its built-in error handling system to raise your own custom errors as well. </li></ul><ul><li>This is accomplished via a function named trigger_error(), which allows you to raise any of the three error types reserved for users: E_USER_NOTICE, E_USER_WARNING and E_USER_ERROR. </li></ul><ul><li>When these errors are triggered, PHP's built-in handler will automatically wake up to handle them. </li></ul><ul><li>Example(triggerror6.php): </li></ul>
  21. 21. Example(triggerror6.php): <ul><li>< ?php </li></ul><ul><li>// function to test a number </li></ul><ul><li>// generates E_USER_WARNING if number is a float </li></ul><ul><li>// generates E_USER_ERROR is number is negative </li></ul><ul><li>function testNumber($num) { </li></ul><ul><li>// float </li></ul><ul><li>// trigger a warning </li></ul><ul><li>if ( is_float ($num)) { </li></ul><ul><li>trigger_error (&quot;Number $num is not an integer&quot;, E_USER_WARNING); </li></ul><ul><li>} </li></ul><ul><li>// negative </li></ul><ul><li>// trigger a fatal error </li></ul><ul><li>if ($num < 0 ) { </li></ul><ul><li>trigger_error (&quot;Number $num is negative&quot;, E_USER_ERROR); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>// test the function with different values </li></ul><ul><li>testNumber ( 100 ) ; </li></ul><ul><li>testNumber ( 5.6 ) ; </li></ul><ul><li>testNumber ( -8 ) ; </li></ul><ul><li>? > </li></ul><ul><li>----output----- </li></ul><ul><li>Warning : Number 5.6 is not an integer in C:wampwww est2part12 riggerror6.php on line 10 </li></ul><ul><li>Fatal error : Number -8 is negative in C:wampwww est2part12 riggerror6.php on line 16 </li></ul>
  22. 22. Pulling the Trigger (cont..) <ul><li>The next example rewrites the previous script to use a user-defined error handler to have a custom error handler to handle your custom errors. </li></ul><ul><li>Example(triggererror7.php): </li></ul>
  23. 23. Example(triggererror7.php): <ul><li>< ?php </li></ul><ul><li>// function to test a number </li></ul><ul><li>// generates E_USER_WARNING if number is a float </li></ul><ul><li>// generates E_USER_ERROR is number is negative </li></ul><ul><li>function testNumber ( $num ) { </li></ul><ul><li>// float </li></ul><ul><li>// trigger a warning </li></ul><ul><li>if ( is_float( $num )) { </li></ul><ul><li>trigger_error ( &quot;Number $num is not an integer&quot;, E_USER_WARNING); </li></ul><ul><li>} </li></ul><ul><li>// negative </li></ul><ul><li>// trigger a fatal error </li></ul><ul><li>if ($num < 0 ) { </li></ul><ul><li>trigger_error (&quot;Number $num is negative“ , E_USER_ERROR); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>// custom error handler </li></ul><ul><li>function myErrorHandler($type, $msg, $file, $line, $context) { </li></ul><ul><li>switch ($type) { </li></ul><ul><li>// warnings </li></ul><ul><li>case E_USER_WARNING: </li></ul><ul><li>// report error </li></ul><ul><li>print &quot;Non-fatal error on line $line of $file: $msg <br />&quot; ; </li></ul><ul><li>break ; </li></ul>
  24. 24. <ul><li>// fatals </li></ul><ul><li>case E_USER_ERROR: </li></ul><ul><li>// report error and die() </li></ul><ul><li>die ( &quot;Fatal error on line $line of $file: $msg <br />&quot; ); </li></ul><ul><li>break ; </li></ul><ul><li>// notices </li></ul><ul><li>default : </li></ul><ul><li>// do nothing </li></ul><ul><li>break ; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>// set the name of the custom handler </li></ul><ul><li>set_error_handler ( 'myErrorHandler' ) ; </li></ul><ul><li>// test the function with different values </li></ul><ul><li>testNumber( 100 ); </li></ul><ul><li>testNumber( 5.6 ); </li></ul><ul><li>testNumber( -8 ); </li></ul><ul><li>? > </li></ul><ul><li>-----output----- </li></ul><ul><li>Non-fatal error on line 10 of C:wampwww est2part12 riggerror7.php: Number 5.6 is not an integer </li></ul><ul><li>Fatal error on line 16 of C:wampwww est2part12 riggerror7.php: Number -8 is negative </li></ul>
  25. 25. Catching up <ul><li>In the exception-based approach, program code is wrapped in a try() block, and exceptions generated by it are &quot;caught&quot; and resolved by a catch() block. </li></ul><ul><li>Multiple catch() blocks are possible, each one dealing with a different error type; this allows developers to trap different types of errors and execute appropriate exception-handling. </li></ul><ul><li>When PHP encounters code wrapped within a try-catch() block: </li></ul><ul><ul><li>It first attempts to execute the code within the try() block. </li></ul></ul><ul><ul><li>If this code is processed without any exceptions being generated, control transfers to the lines following the try-catch() block. </li></ul></ul><ul><ul><li>If an exception is generated while running the code within the try() block, PHP stops execution of the block at that point and begins checking each catch() block to see if there is a handler for the exception. </li></ul></ul><ul><ul><li>If a handler is found, the code within the appropriate catch() block is executed; if not, a fatal error is generated. </li></ul></ul>
  26. 26. Catching up (cont..) <ul><li>The exceptions themselves are generated via PHP's throw statement. </li></ul><ul><li>The throw statement needs to be passed a descriptive message, and an optional error code. </li></ul><ul><li>When the exception is raised, this description and code will be made available to the exception handler. </li></ul><ul><li>Example(tryncatcherror8.php): </li></ul>
  27. 27. <ul><li>< ?php </li></ul><ul><li>// PHP 5 </li></ul><ul><li>error_reporting ( 0 ); </li></ul><ul><li>// try this code </li></ul><ul><li>try { </li></ul><ul><li>$file = 'somefile.txt' ; </li></ul><ul><li>// open file </li></ul><ul><li>if ( ! $fh = fopen ($file, 'r' )) { </li></ul><ul><li>throw new Exception( 'Could not open file!' ); </li></ul><ul><li>} </li></ul><ul><li>// read file contents </li></ul><ul><li>if ( ! $data = fread ($fh, filesize ($file ))) { </li></ul><ul><li>throw new Exception( 'Could not read file!' ); </li></ul><ul><li>} </li></ul><ul><li>// close file </li></ul><ul><li>fclose ($fh); </li></ul><ul><li>// print file contents </li></ul><ul><li>echo $data; </li></ul><ul><li>} </li></ul><ul><li>// catch errors if any </li></ul><ul><li>catch (Exception $e) { </li></ul><ul><li>print 'Something bad just happened...' ; </li></ul><ul><li>} </li></ul><ul><li>?> </li></ul><ul><li>----output---- </li></ul><ul><li>Something bad just happened... </li></ul>Example (tryncatcherror8.php):
  28. 28. Catching up (cont..) <ul><li>If the file doesn't exist or is unreadable, the throw statement will generate an exception (basically, an instance of PHP's built-in Exception object) and pass it a message describing the error. </li></ul><ul><li>When such an exception is generated, control passes to the first catch() block. </li></ul><ul><li>If the catch() block can handle the exception type, the code within the catch() block is executed. </li></ul><ul><li>If the first catch() block cannot handle the generated exception, control passes to the next one. </li></ul>
  29. 29. Example (tryncatcherror9.php) <ul><li>< ?php // PHP 5 error_reporting (0); // try this code try {     $file = 'somefile.txt ';      // open file      if ( ! $fh = fopen ($file, 'r’ )) {         throw new Exception( 'Could not open file!' , 12);     }      // read file contents      if ( ! $data = fread ($fh, filesize ($file))) {         throw new Exception('Could not read file!', 9);     }     // close file      fclose ($fh);      // print file contents      echo $data; } // catch errors if any catch (Exception $e) {      print '<h2>Exception</h2>‘ ; </li></ul><ul><li>     print 'Error message: ' . $e -> getMessage () . '<br />‘ ;      print 'Error code: ' . $e -> getCode () . '<br />‘ ;      print 'File and line: ' . $e -> getFile (). '(' . $e->getLine () . ‘)<br />‘ ;      print 'Trace: ' . $e -> getTraceAsString () . '<br /> '; } ? > </li></ul><ul><li>----output---- </li></ul><ul><li>Exception </li></ul><ul><li>Error message: Could not open file! Error code: 12 File and line: C:wampwww est2part12 ryncatcherror9.php(12) Trace: #0 {main} </li></ul>
  30. 30. Catching up (cont..) <ul><li>When you run this script, you'll see that the message generated by the exception handler contains: </li></ul><ul><ul><li>the descriptive data sent by throw, </li></ul></ul><ul><ul><li>an error code (also sent by throw), </li></ul></ul><ul><ul><li>the file name and line number where the exception occurred, and a stack trace indicating the exception's progress through the class hierarchy, if there is one. </li></ul></ul><ul><li>This data is generated by calling the Exception object's getMessage(), getCode(), getFile(), getLine() and getTraceAsString() methods respectively inside the catch() block. </li></ul><ul><li>. </li></ul>
  31. 31. Adding Some Class <ul><li>You can handle different exceptions in different ways, by sub-classing the generic Exception object and using more than one catch() block. </li></ul><ul><li>Example(classerror10.php): </li></ul><ul><ul><li>Note that because PHP will always use the first catch() block that matches the exception type and because the generic Exception class matches all exceptions, the catch() blocks must be arranged in the order of most specific first . </li></ul></ul>
  32. 32. Example (classerror10.php) <ul><li>< ?php </li></ul><ul><li>// PHP 5 </li></ul><ul><li>// sub-class the Exception class </li></ul><ul><li>class NegativeNumException extends Exception {} </li></ul><ul><li>//class OutOfRangeException extends Exception {} </li></ul><ul><li>class FloatException extends Exception {} </li></ul><ul><li>// function to test a number </li></ul><ul><li>function testNumber($num) { </li></ul><ul><li>// float </li></ul><ul><li>// trigger an exception </li></ul><ul><li>if (is_float($num )) { </li></ul><ul><li>throw new FloatException($num); </li></ul><ul><li>} </li></ul><ul><li>// negative </li></ul><ul><li>// trigger an exception </li></ul><ul><li>if ($num < 0 ) { </li></ul><ul><li>throw new NegativeNumException($num); </li></ul><ul><li>} </li></ul><ul><li>// out of range </li></ul><ul><li>// trigger an exception </li></ul><ul><li>if ($num > 1000 || $num < 100 ) { </li></ul><ul><li>throw new OutOfRangeException($num); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  33. 33. <ul><li>// try this code </li></ul><ul><li>try { </li></ul><ul><li>testNumber (- 19 ) ; </li></ul><ul><li>} </li></ul><ul><li>// catch errors, if any </li></ul><ul><li>catch ( NegativeNumException $e ) { </li></ul><ul><li>print 'A negative number was provided (' . $e -> getMessage (). '). Please provide a positive integer between 100 and 1000.<br />' ; </li></ul><ul><li>} </li></ul><ul><li>catch ( OutOfRangeException $e ) { </li></ul><ul><li>print 'The number provided is out of range (' . $e -> getMessage (). '). Please provide a positive integer between 100 and 1000.<br />' ; </li></ul><ul><li>} </li></ul><ul><li>catch (FloatException $e) { </li></ul><ul><li>print 'The number provided is not an integer (' . $e -> getMessage (). '). Please provide a positive integer between 100 and 1000.<br />' ; </li></ul><ul><li>} </li></ul><ul><li>catch (Exception $e) { </li></ul><ul><li>print 'Error message: ' . $e -> getMessage () . '<br />' ; </li></ul><ul><li>print 'Error code: ' . $e -> getCode () . '<br />' ; </li></ul><ul><li>print 'File and line: ' . $e -> getFile () . '(' . $e->getLine() . ')<br />' ; </li></ul><ul><li>print 'Trace: ' . $e -> getTraceAsString () . '<br />' ; </li></ul><ul><li>} </li></ul><ul><li>?> </li></ul><ul><li>----output---- </li></ul><ul><li>A negative number was provided (-19). Please provide a positive integer between 100 and 1000. </li></ul>
  34. 34. <ul><li>Here's another example, this one illustrating a more useful application - using the exception model in a user authentication class to provide easy-to-understand error handling </li></ul><ul><li>Example(classerror11.php) </li></ul><ul><li>Here, depending on the type of error, either a FileException() or an AuthException() will be generated - and handled by the corresponding catch() block </li></ul>
  35. 35. Example (classerror11.php) <ul><li>< ?php </li></ul><ul><li>// PHP 5 </li></ul><ul><li>// class definition </li></ul><ul><li>class userAuth { </li></ul><ul><li>// define properties </li></ul><ul><li>private $username; </li></ul><ul><li>private $passwd; </li></ul><ul><li>private $passwdFile; </li></ul><ul><li>// constructor </li></ul><ul><li>// must be passed username and non-encrypted password </li></ul><ul><li>public f unction __construct($username, $password) { </li></ul><ul><li>$this-> username = $username; </li></ul><ul><li>$this-> passwd = $password; </li></ul><ul><li>} </li></ul><ul><li>// set .htaccess-style file to check for passwords </li></ul><ul><li>public function setPasswdFile($file) { </li></ul><ul><li>$this-> passwdFile = $file; </li></ul><ul><li>} </li></ul><ul><li>// perform password verification </li></ul><ul><li>public function authenticateUser() { </li></ul><ul><li>// check that the file exists </li></ul><ul><li>if ( !file_exists ( $this-> passwdFile)) { </li></ul><ul><li>throw new FileException( &quot;Password file cannot be found: &quot; . $this-> passwdFile); </li></ul><ul><li>} </li></ul>
  36. 36. <ul><li>// check that the file is readable </li></ul><ul><li>if ( !is_readable ( $this->passwdFile )) { </li></ul><ul><li>throw new FileException( &quot;Unable to read password file: &quot; . $this-> passwdFile); </li></ul><ul><li>} </li></ul><ul><li>// read file </li></ul><ul><li>$data = file ( $this-> passwdFile); </li></ul><ul><li>// iterate through file </li></ul><ul><li>foreach ($data as $line) { </li></ul><ul><li>$arr = explode ( &quot;:&quot; , $line); </li></ul><ul><li>// if username matches, test password </li></ul><ul><li>if ($arr [ 0 ] == $this-> username) { </li></ul><ul><li>// get salt and crypt(), assuming encryption </li></ul><ul><li>$salt = substr ($arr[ 1 ], 0 , 2 ); </li></ul><ul><li>// if match, user/pass combination is correct </li></ul><ul><li>if ($arr [ 1 ] == crypt ( $this-> passwd, $salt)) { </li></ul><ul><li>echo &quot;User was authenticated&quot; ; </li></ul><ul><li>// do some other stuff </li></ul><ul><li>} </li></ul><ul><li>// otherwise return exception </li></ul><ul><li>else { </li></ul><ul><li>throw new AuthException( &quot;Incorrect password&quot; ); </li></ul><ul><li>break ; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>else { </li></ul><ul><li>// could not find a username match </li></ul><ul><li>// return exception </li></ul><ul><li>throw new AuthException( &quot;No such user&quot; ); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>// end class definition </li></ul><ul><li>} </li></ul>
  37. 37. <ul><li>// subclass exceptions </li></ul><ul><li>class FileException extends Exception {} ; </li></ul><ul><li>class AuthException extends Exception {} ; </li></ul><ul><li>// try the code </li></ul><ul><li>try { </li></ul><ul><li>// create instance </li></ul><ul><li>$ua = new userAuth ( &quot;joe&quot; , &quot;secret&quot; ) ; </li></ul><ul><li>// set password file </li></ul><ul><li>$ua -> setPasswdFile ( &quot;password.txt&quot; ) ; </li></ul><ul><li>// perform authentication </li></ul><ul><li>$ua -> authenticateUser () ; </li></ul><ul><li>} </li></ul><ul><li>// catch authentication failures, if any </li></ul><ul><li>catch ( FileException $e ) { </li></ul><ul><li>// print file errors </li></ul><ul><li>print &quot;A file error occurred. &quot; . $e -> getMessage () ; </li></ul><ul><li>} </li></ul><ul><li>catch ( AuthException $e ) { </li></ul><ul><li>// an authentication error occurred </li></ul><ul><li>print &quot;An authentication error occurred. &quot; . $e -> getMessage(); </li></ul><ul><li>// more normally, redirect to new page on auth errors, e.g. </li></ul><ul><li>// header ('Location: login_fail.php'); </li></ul><ul><li>} </li></ul><ul><li>catch (Exception $e) { </li></ul><ul><li>print &quot;An unknown error occurred&quot; ; </li></ul><ul><li>} </li></ul><ul><li>? > </li></ul><ul><li>----output--- </li></ul><ul><li>A file error occurred. Password file cannot be found: password.txt </li></ul>
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×