CSCI 215 Web Programming II Debugging & Error Handling.

Slides:



Advertisements
Similar presentations
JQuery MessageBoard. Lets use jQuery and AJAX in combination with a database to update and retrieve information without refreshing the page. Here we will.
Advertisements

Error HandlingPHPMay-2007 : [#] PHP Error Handling.
A MATLAB function is a special type of M-file that runs in its own independent workspace. It receives input data through an input argument list, and returns.
Why care about debugging? How many of you have written a program that worked perfectly the first time? No one (including me!) writes a program that works.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Java Programming, 3e Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
1 Working With PHP David Lash Module 1 Getting Started.
General Computer Science for Engineers CISC 106 Lecture 21 Dr. John Cavazos Computer and Information Sciences 04/10/2009.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Intro To PHP David Lash Getting Started With PHP.
Chapter 2: Input, Processing, and Output
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
JavaScript, Fourth Edition
Testing a program Remove syntax and link errors: Look at compiler comments where errors occurred and check program around these lines Run time errors:
ITM 352 © Port,KazmanDebugging - 1 ITM 352 Debugging.
Lecture 8 : PHP Errors & Exceptions UFCFR Advanced Topics in Web Development II 2014/15 SHAPE Hong Kong.
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering.
Exceptions COMPSCI 105 S Principles of Computer Science.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP Form Handling.
INTERNET APPLICATION DEVELOPMENT For More visit:
2010/11 : [1]Building Web Applications using MySQL and PHP (W1)PHP Recap.
Throwing and Catching Exceptions Tran Anh Tuan Edit from Telerik Software Academy
ASP.NET Programming with C# and SQL Server First Edition Chapter 6 Debugging and Error Handling.
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
1 Chapter 9 Writing, Testing, and Debugging Access Applications.
Lesson 19. JavaScript errors Since JavaScript is an interpreted language, syntax errors will usually cause the script to fail. Both browsers will provide.
PHP Workshop ‹#› PHP Error Handling. PHP Workshop ‹#› Types There are 12 unique error types, which can be grouped into 3 main categories: Informational.
BİL528 – Bilgisayar Programlama II Making Decisions, Loops, Debugging, Designing Objects Using Classes 1.
PHP - Basic Language Constructs CSCI 297 Scripting Languages - Day Two.
Testing. 2 Overview Testing and debugging are important activities in software development. Techniques and tools are introduced. Material borrowed here.
Introduction to Exception Handling and Defensive Programming.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
Controlling Execution Programming Right from the Start with Visual Basic.NET 1/e 8.
FT228/3 Web Development Error processing. Introduction READ Chapter 9 of Java Server Pages from O’reilly 2 nd Edition Need to be able to 1) Diagnose and.
Storing and Retrieving Data
Server-Side Scripting with PHP ISYS 475. PHP Manual Website
8 th Semester, Batch 2008 Department Of Computer Science SSUET.
Lecture 2 Conditional Statement. chcslonline.org Conditional Statements in PHP Conditional Statements are used for decision making. Different actions.
Java Programming, 2E Introductory Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
PHP Error Handling & Reporting. Error Handling Never allow a default error message or error number returned by the mysql_error() and mysql_errno() functions.
PHP Error Handling Section :I Source: 1.
Firoze Abdur Rakib. Syntax errors, also known as parsing errors, are perhaps the most common kind of error you encounter while you are still learning.
Chapter 8 Error Handling and Debugging. Debugging “When you get frustrated, step away from the computer!”
8 th Semester, Batch 2008 Department Of Computer Science SSUET.
Basic Scripting & Variables Yasar Hussain Malik - NISTE.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
Creating FunctionstMyn1 Creating Functions Function can be divided into two groups: –Internal (built in) functions –User-defined functions.
JavaScript, Sixth Edition
JavaScript and Ajax (Control Structures) Week 4 Web site:
PHP (cont.). 2 Functions Definition – function name(arguments){... } –syntax name as for a variable, but without $ arguments as for variables –to return.
Exception Handling How to handle the runtime errors.
PHP Exception Handling How to handle and create user-defined exceptions Mario Peshev Technical Trainer Software University
Martin Kruliš Who is General Failure and why is he reading my disk? by Martin Kruliš (v1.0)1.
CIS 133 Mashup Javascript, jQuery and XML Chapter 8 Debugging and Error Handling.
Introduction to Exceptions in Java CS201, SW Development Methods.
CS 174: Web Programming October 21 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
ITM 352 © Port,KazmanFile I/O - 1 File I/O in PHP Persistent Data.
ITM 352 Debugging.
Scripts & Functions Scripts and functions are contained in .m-files
ITM 352 Flow-Control: Loops
Error Handling and Validation
תיכון אהל שם, רמת גן קורס PHP – הרצאת העשרה
ITM 352 Debugging.
An Introduction to Debugging
Error Handling and Debugging
Debugging and Handling Exceptions
PHP Parse error Fatal error Warning Notice Updated : August 23,2012
Presentation transcript:

CSCI 215 Web Programming II Debugging & Error Handling

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

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 Parse Error

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

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

Notices <?php error_reporting(E_ALL); echo ' Error 1: Undefined variable: '; echo $undefined_var; echo ' Error 2: Unquoted string: '; $some_var = tryetrhrtdf; ?>

Notices

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

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

PHP Programming11 Warnings

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'); ?>

Warnings

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

Fatal Errors <? error_reporting(E_ALL); echo ' Error 1: Undefined function: '; $fp = non_existing_function('an_arg'); echo 'Code never gets here!!!'; ?>

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); } …

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

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

PHP Programming19

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

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

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!!!';

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!

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

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.

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

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

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);

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

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!!!';

/215/error_handling/error5.php

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

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

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

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

Use Comments to Debug $Amount = ; $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

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'];

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

Learn More