PHP Programming3"> PHP Programming3">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSCI 215 Web Programming II Debugging & Error Handling.

Similar presentations


Presentation on theme: "CSCI 215 Web Programming II Debugging & Error Handling."— Presentation transcript:

1 CSCI 215 Web Programming II Debugging & Error Handling

2 Error Types Parse (syntax) errors ◦ Occur when the scripting engine fails to recognize code ◦ Example: Incorrectly spelled or mistyped words Run-time errors ◦ Occur when the engine encounters a problem while program is running ◦ Example: Division by zero Logic errors ◦ Flaws in program design that prevent the program from running as intended ◦ Example: Infinite loop 2

3 Parse Error 11 <?php 12 for ($count = 10; $count >= 0; --$count) 13if ($count == 0) 14 echo " We have liftoff! "; 15else 16 echo " Liftoff in $count seconds. "; 17 } 18 ?> PHP Programming3

4 4 Parse Error

5 Run-Time Errors E_NOTICE Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. E_USER_NOTICE User-generated notice message, generated by trigger_error(). trigger_error() E_WARNING Run-time warnings (non-fatal errors). Execution of the script is not halted. E_USER_WARNING User-generated warning message, generated by trigger_error(). trigger_error() E_COMPILE_WARNING Fatal compile-time errors. E_CORE_WARNING Warnings that occur during PHP's initial startup. E_ERROR Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted. E_USER_ERROR User-generated error message, generated by trigger_error().trigger_error() E_COMPILE_ERROR Fatal compile-time errors. E_CORE_ERROR Fatal errors that occur during PHP's initial startup. E_PARSE Compile-time parse (syntax) errors. notices warnings fatal errors

6 Notices Raised for potential run-time errors that do not prevent a script from executing Examples ◦ use of an undefined variable ◦ defining a string without quotes PHP Programming6

7 Notices <?php error_reporting(E_ALL); echo ' Error 1: Undefined variable: '; echo $undefined_var; echo ' Error 2: Unquoted string: '; $some_var = tryetrhrtdf; ?> http://ned.highline.edu/~tostrander/215/error_handling/error1.php

8 Notices

9 Warnings Do not prevent a script from executing Indicate that something clearly wrong has happened and action should be taken. Examples: ◦ File not found ◦ Database not available ◦ Missing function arguments PHP Programming9

10 Warnings function beginCountdown($time) { if (!isset($time)) $time = 10; for ($count = $time; $count >= 0; —$count) { if ($count == 0) echo ' We have liftoff! '; else echo " Liftoff in $count seconds. "; } beginCountdown(); PHP Programming10

11 PHP Programming11 Warnings

12 Warnings <? echo ' Error 1: file not available: '; $fp = fopen('file_does_not_exist.dat','r'); echo ' Error 2: db not available: '; $results = mysql_query('SOME QUERY'); ?> http://ned.highline.edu/~tostrander/215/error_handling/error2.php

13 Warnings

14 Fatal Errors Raised when a run-time error prevents a script from executing Something so terrible has happened during execution of your script that processing cannot continue. Examples: ◦ Parse error ◦ Calling an undefined function PHP Programming14

15 Fatal Errors <? error_reporting(E_ALL); echo ' Error 1: Undefined function: '; $fp = non_existing_function('an_arg'); echo 'Code never gets here!!!'; ?> http://ned.highline.edu/~tostrander/215/error_handling/error3.php

16 Raising Errors It is possible to force a PHP error at any point in your script. trigger_error($msg, $type); Example: if (!$name) { trigger_error('No name entered', E_USER_ERROR); } …

17 trigger_error() trigger_error() accepts two arguments: ◦ A custom error message ◦ The error reporting level  E_USER_ERROR  E_USER_WARNING  E_USER_NOTICE PHP Programming17

18 if (isset($_GET['height']) && isset($_GET['weight'])) { if (!is_numeric($_GET['weight']) || !is_numeric($_GET['height'])) { trigger_error(“User did not enter numeric values”, E_USER_ERROR); } } else { trigger_error(“Values not entered”, E_USER_ERROR); } $bodyMass = $_GET['weight'] / ($_GET['height'] * $_GET['height']) * 703; print "Your body mass index is $bodyMass"; PHP Programming18

19 PHP Programming19

20 php.ini Directives display_errors ◦ prints script error messages ◦ default value of “On” error_reporting ◦ determines which types of error messages PHP should generate ◦ by default, assigned a value of “E_ALL” PHP Programming20

21 Set Error Reporting Level error_reporting($level) Used to control which errors are displayed, and which are ignored. Only lasts for the duration of your script

22 ini_set('display_errors', 1); // turn all error reporting ON // error_reporting(E_ALL); // Report all errors except E_NOTICE // error_reporting(E_ALL ^ E_NOTICE); // Turn off all error reporting error_reporting(0); // generate errors echo ' Error 1: Use of an undefined variable. '; echo $undefined_var; echo ' Error 2: Use of an unquoted string. '; $some_var = tryetrhrtdf; echo ' Error 3: file not available: '; $fp = fopen('this_file_does_not_exist.dat','r'); echo ' Error 4: db not available: '; $results = mysql_query('SOME QUERY'); echo ' Error 5: call to undefined function: '; $fp = non_existing_function('an_arg'); echo 'Code never gets here!!!';

23 http://ned.highline.edu/~tostrander/215/error_handling/error4.php

24 Hiding Errors Hiding errors is NOT a solution to a problem. It is useful, however, to hide any errors produced on a live server. While developing and debugging code, displaying all errors is highly recommended!

25 Suppressing Errors The special @ operator can be used to suppress function errors Any error produced by the function is suppressed regardless of the error reporting setting. $db = @mysql_connect($h,$u,$p); if (!$db) { trigger_error(‘blah’, E_USER_ERROR); }

26 Suppressing Errors Error suppression is NOT a solution to a problem. It can be useful to locally define your own error handling mechanisms. If you suppress errors, you must check for them yourself elsewhere.

27 Custom Error Handling You can write your own function to handle PHP errors however you want. The handler function should receive four arguments The handler function should return true to indicate it has handled the error Register the function in your script as the error handler

28 Custom Error Handling function err_handler( $errcode, $errmsg, $file, $lineno) { echo ‘An error has occurred! ’; echo “file: $file ”; echo “line: $lineno ”; echo “Problem: $errmsg”; return true; } The handler must have 4 inputs.. 1. error code 2. error message 3. file where error occurred 4. line at which error occurred The handler must have 4 inputs.. 1. error code 2. error message 3. file where error occurred 4. line at which error occurred

29 Custom Error Handling The function then needs to be registered as your custom error handler: set_error_handler(‘err_handler’); You can ‘mask’ the custom error handler so it only receives certain types of errors ◦ Example: register a custom handler just for user triggered errors set_error_handler(‘err_handler’, E_USER_NOTICE | E_USER_WARNING | E_USER_ERROR);

30 Custom Error Handler A custom error handler is never passed E_PARSE, E_CORE_ERROR or E_COMPILE_ERROR errors These are considered too dangerous

31 function err_handler($errcode,$errmsg,$file,$lineno) { echo 'An error has occurred! '; echo "file: $file "; echo "line: $lineno "; echo "Problem: $errmsg "; return true; } set_error_handler('err_handler'); // register handler echo ' Error 1: Use of an undefined variable. '; echo $undefined_var; echo ' Error 2: Use of an unquoted string. '; $some_var = tryetrhrtdf; echo ' Error 3: file not available: '; $fp = fopen('this_file_does_not_exist.dat','r'); echo ' Error 4: db not available: '; $results = mysql_query('SOME QUERY'); echo ' Error 5: call to undefined function: '; $fp = non_existing_function('an_arg'); echo 'Code never gets here!!!';

32 http://ned.highline.edu/~tostrander /215/error_handling/error5.php

33 Other Tips Trace errors Follow coding standards Write stub functions “Comment out” problematic lines Analyze logic carefully PHP Programming33

34 Trace Errors Tracing is the examination of individual statements in an executing program echo one of the most useful ways to trace PHP code Use echo to display the contents of a variable, an array, or the value returned from a function PHP Programming34

35 function calculatePay() { $PayRate = 15; $NumHours = 40; $GrossPay = $PayRate * $NumHours; echo “Gross Pay: $GrossPay ”; $FederalTaxes = $GrossPay *.06794; $StateTaxes = $GrossPay *.0476; $SocialSecurity = $GrossPay *.062; $Medicare = $GrossPay *.0145; $NetPay = $GrossPay - $FederalTaxes; echo “Net Pay 1: $NetPay ”; $NetPay *= $StateTaxes; echo “Net Pay 2: $NetPay ”; $NetPay *= $SocialSecurity; echo “Net Pay 3: $NetPay ”; $NetPay *= $Medicare; echo “Net Pay 4: $NetPay ”; return number_format($NetPay, 2); } PHP Programming35

36 Stub Functions function calcTax($amount) { return 1; } function isValid($email) { return true; } Stubs return a hard-coded value "Stubs" are empty functions that serve as placeholders for a program’s actual functions

37 Use Comments to Debug $Amount = 100000; $Percentage =.08; printf(“The interest rate or a loan in the amount of $%.2f is %s%. ”, $Amount, $Percentage * 100); $YearlyInterest = $Amount * $Percentage; // printf(“The amount of interest for one year is // $%.2f. ”, $YearlyInterest); // $MonthlyInterest = $YearlyInterest / 12; // printf(“The amount of interest for one month is // $%.2f. ”, $MonthlyInterest); // $DailyInterest = $YearlyInterest / 365; // printf(“The amount of interest for one day is $%.2f. // ”, $DailyInterest); PHP Programming37 The cause of an error in a statement is often the result of an error in a preceding statement

38 Analyze Logic Logic errors are the hardest to debug You must analyze each statement carefully PHP Programming38 if (!isset($_GET['firstName'])) echo “You must enter your first name!”; exit(); echo “Welcome to my Web site, ”. $_GET['firstName'];

39 Analyze Logic PHP Programming39 for ($count = 1; $count < 6; $count++); echo “$count ”; $n = 1; while($n < 10){ echo $n; } Isolate problematic code

40 Learn More http://www.w3schools.com/php/php_error.asp


Download ppt "CSCI 215 Web Programming II Debugging & Error Handling."

Similar presentations


Ads by Google