Lecture 8 : PHP Errors & Exceptions UFCFR5-15-3 Advanced Topics in Web Development II 2014/15 SHAPE Hong Kong.

Slides:



Advertisements
Similar presentations
Error HandlingPHPMay-2007 : [#] PHP Error Handling.
Advertisements

Error-handling using exceptions
Topics Introduction Types of Errors Exceptions Exception Handling
COMPUTER PROGRAMMING I Essential Standard 5.02 Understand Breakpoint, Watch Window, and Try And Catch to Find Errors.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
Debugging Techniques1. 2 Introduction Bugs How to debug Using of debugger provided by the IDE Exception Handling Techniques.
CSCI 215 Web Programming II Debugging & Error Handling.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
ITM 352 © Port,KazmanDebugging - 1 ITM 352 Debugging.
Kyle MacLachlan.  Used To Format a Date/Time  Syntax: › date(format,timestamp)  format: Required, specifies format  timestamp:Optional, specifies.
Apply Sub Procedures/Methods and User Defined Functions
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP Form Handling.
Throwing and Catching Exceptions Tran Anh Tuan Edit from Telerik Software Academy
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
Object Oriented Programming
Handling ErrorstMyn1 Handling Errors Up to this point we haven't worried much about errors or exceptions. First, let's distinguish between errors and exceptions.
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.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
COMPUTER PROGRAMMING 2 Exceptions. What are Exceptions? Unexpected events that happen when the code is executing (during runtime). Exceptions are types.
PHP3. PHP File Upload With PHP, it is possible to upload files to the server. Create an Upload-File Form To allow users to upload files from a form can.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
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.
Exceptions Handling Exceptionally Sticky Problems.
How to Design Error Steady Code Ivaylo Bratoev Telerik Corporation
Object Oriented Software Development 8. Exceptions, testing and debugging.
Introduction to Exception Handling and Defensive Programming.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
CISC 3140 (CIS 20.2) Design & Implementation of Software Application II Instructor : M. Meyer Address: Course Page:
ICS 313: Programming Language Theory Chapter 14: Exceptions.
Lecture 2 Conditional Statement. chcslonline.org Conditional Statements in PHP Conditional Statements are used for decision making. Different actions.
PHP Error Handling Section :I Source: 1.
Exceptions and Assertions Chapter 15 – CSCI 1302.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
8 th Semester, Batch 2008 Department Of Computer Science SSUET.
Creating FunctionstMyn1 Creating Functions Function can be divided into two groups: –Internal (built in) functions –User-defined functions.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
IMS 3253: Validation and Errors 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Validation and Error Handling Validation.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
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.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Introduction to Exceptions in Java CS201, SW Development Methods.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Eighth Lecture Exception Handling in Java
ITM 352 Debugging.
Computer Programming I
Topics Introduction to File Input and Output
Part B – Structured Exception Handling
Exceptions 19-Feb-19.
ITM 352 Debugging.
Debugging and Handling Exceptions
Topics Introduction to File Input and Output
Exception Handling.
Presentation transcript:

Lecture 8 : PHP Errors & Exceptions UFCFR Advanced Topics in Web Development II 2014/15 SHAPE Hong Kong

Why handle errors/exceptions? o Produce more stable code - programs run longer without failing in the “wild” o Code is easier to debug o Code is easier to maintain o Logging allows for traceability – improves security o Traps fatal events gracefully o Improves the life of users/programmers But.. o Can’t account for every eventually.... problem of closure – cost/benefit analysis required o Don’t over-do it! e.g. too much logging can slow performance. Find the right balance …

o Basically errors can be of one of two types - External Errors (usually resource unavailability) - Logic Errors (a.k.a. Bugs) o What about these error types? - External Errors will always occur at some point or another - External Errors which are not accounted for are Logic Errors (of a kind) - Logic Errors are harder to track down Error Types

Four levels of error severity to start with - Strict standard problems (E_STRICT)E_STRICT - Notices (E_NOTICE)E_NOTICE - Warnings (E_WARNING)E_WARNING - Errors (E_ERROR)E_ERROR Others include E_ALL, E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE PHP’s Internal Handlers

o E_STRICT - messages that provide suggestions on improving code to reduce ambiguities and make code more portable o E_NOTICE - a runtime message that indicates something that might produce an unexpected result depending on the context o E_WARNING - a non-fatal run time error. Scripts continue to execute o E_ERROR - fatal runtime errors. Scripts stop executing. PHP’s Internal Handlers (2)

<?php // E_NOTICE $x = $y + 3; // E_WARNING $fh = fopen('thisisnotarealfile', 'r'); // E_ERROR nonExistingFunction(); ?> Notice: Undefined variable: y in J:\xampp\htdocs\error_example1.php on line 3 Warning: fopen(thisisnotarealfile) [function.fopen]: failed to open stream: No such file or directory in J:\xampp\htdocs\error_example1.php on line 5 Fatal error: Call to undefined function nonExistingFunction() in J:\xampp\htdocs\error_example1.php on line 7function.fopen PHP’s Internal Handlers Example

o Almost the same as the ones in the previous slides - User triggered notice (E_USER_NOTICE) - User triggered warning (E_USER_WARNING) - User triggered error (E_USER_ERROR) o Triggering them is done using trigger_error() <?php function getValPlusOne($val) { if (3 > $val) { trigger_error('val has to be greater than 3', E_USER_ERROR); } return ($foo + 1); } // trigger error $val = 2; $val = GetValPlusOne($val); ?> User Triggered Error

Additional Error Types o Catchable fatal error - E_RECOVERABLE_ERROR – a probably dangerous error occurred. If not handled by the user, the application will abort as if this was an E_ERROR o Parsing errors - E_PARSE – there is a syntactic error found while parsing the script. This is a fatal error o Compilation errors - E_COMPILE_ERROR – a fatal error occurred in the engine while compiling the script - E_COMPILE_WARNING - a nonfatal error occurred in the engine while compiling the script o PHP core errors - E_CORE_ERROR – a fatal runtime error occurred in the engine - E_CORE_WARNING – a nonfatal runtime error occurred in the engine

o Setting which errors PHP will report is done through the error_reporting directive - in php.ini file error_reporting = E_ALL & ~E_NOTICE - at runtime error_reporting(E_ALL & ~E_NOTICE); - in.htaccess or apache.conf php_value error_reporting 6135 Error Reporting Configuration Settings

Handling Errors o There are four ways to handle errors - Display them - Log them - Ignore them - Act on them Relevance of image??

Displaying Errors o How to display errors in the standard output - - Set the display_errors directive to On - Set the error_reporting to the appropriate severity level Displaying errors is good for the programmer but bad for the user

Logging Errors o How to set PHP to automatically log errors - Set the log_errors directive to On - Set the error_log directive to your preferred logging option o PHP supports two options for logging errors - Logging to a file – set the error_log to a file path - Logging to syslog – set the error_log to syslog

Ignoring Errors

Here’s what happens to your assignment mark if you forget error / exception handling. Likely to be in exam also.. Relevance of image …

Acting on Errors o PHP enables us to set a default error handler using the set_error_handler() function o Five parameters will be passed to the user-defined error handler function - integer $errno – error severity level - string $errstr – error message - string $errfile [optional] – filename where the error was raised - integer $errline [optional] – line number where the error was raised - array $errcontext [optional] - an array of every variable that existed in the scope the error was triggered in

function demoErrorHandler($errno, $errstr, $errfile, $errline) { switch ($errno) { case E_USER_ERROR: Logger::log(E_ERROR, $errstr, $errfile, $errline); require_once(FULL_PATH_DEFAULT_ERROR_PAGE); exit(1); // control the flow break; case E_WARNING: case E_USER_WARNING: Logger::log(E_WARNING, $errstr, $errfile, $errline); break; case E_NOTICE: case E_USER_NOTICE: Logger::log(E_NOTICE, $errstr, $errfile, $errline); break; default: Logger::log(0, $errstr, $errfile, $errline); break; } return true; // Avoid running PHP's internal error handler } set_error_handler("demoErrorHandler"); Acting on Errors (2)

o What can the error handler do? - Display a safer message to the user - Insert the data into a DB - Write to a file - Send an ... Acting on Errors (3) Remember that for non-fatal errors, the script will carry on running

External errors will always occur at some point of an application's life-cycle External errors which are not accounted for show up as bugs - likely causes are: o Assuming a DB connection always succeeds o Assuming a file is opened properly o Assuming an XML file has the right format o... Handling External Errors Assumptions about ‘events in’ or ‘states of’ the external world are always risky and bound to the occurrence of a counter-instance sooner or later (Murphy’s Law)Murphy’s Law

$fh 'w'); $fh ->fwrite('save the rhinos!'); $fh = fopen($myfile, 'w'); if ($fh) { $fh->write('save the rhinos!'); } else { redirectToErrorPage('Failed opening an important file'); die(1); } $db = mysql_connect(); mysql_query('SELECT * FROM users WHERE id=18'); $db = mysql_connect(); if (! $db) { redirectToErrorPage('Could not connect to the database!'); die(1); } mysql_query('SELECT * FROM users WHERE id=18', $db); Handling External Errors (2)

An Exception can be thought of as a flow-control structure, or as an error control mechanism o Exceptions should be used to handle logic errors o Exceptions may be considered as any other type of flowcontrol syntax (such as if-else, while and foreach) o Exceptions are slower and consume more memory than other flow-control syntaxes, therefore it is not recommended to use it as a flow-control structure per se Unhandled Exceptions are fatal errors Exceptions

Exceptions are classes and therefore you may extend them to fit your needs or serve as markers class DataBaseException extends Exception { } class MathException extends Exception { } Will make more sense when we get to object-oriented php Exceptions (2)

Terminology: o throw – the act of publishing an Exception o try block – a segment of the code which may have an exception thrown in it o catch block – a segment of the code which handles an exception if one happens o finally – is not available in PHP, but common in other languages Exceptions (3)

try { if (0 == $denominator) { throw new Exception('Zero denominator'); } echo ($numerator / $denominator); } catch (Exception $e) { echo 'You can not divide by zero'; die; // make sure the script stops } Exceptions (4)

Default Exception Handler An user-defined top-level Exception Handler which will handle any uncaught Exception o Unlike a try-catch block, after handling an Exception with the default error handler, the script halts o Note that the default exception handler can not catch all uncaught exceptions which may happen in your code (think about why?) function myDefaultExceptionHandler($exception) { // do something about it } set_exception_handler('myDefaultExceptionHandler');

o Errors happen, but it doesn't mean they should be ignored o Watch out for external errors or they may turn to bugs o Use Exceptions to better handle errors and logic flaws o Use Exceptions to distinguish between different error cases o Have a default error handler and a default exception handler, even if you are sure that everything is covered Conclusions :