PHP Exception Handling How to handle and create user-defined exceptions Mario Peshev Technical Trainer Software University

Slides:



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

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
JavaScript Basics Course Introduction SoftUni Team Technical Trainers Software University
Software Quality Assurance QA Engineering, Testing, Bug Tracking, Test Automation Software University Technical Trainers SoftUni Team.
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.
 Dimitar Ivanov Introduction to programming with microcontrollers.
C# Advanced Topics Methods, Classes and Objects SoftUni Team Technical Trainers Software University
PHP Flow Control Loops, Functions, Return, Exit, Require, Try...Catch Software University SoftUni Team Technical Trainers.
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Methods Writing and using methods, overloads, ref, out SoftUni Team Technical Trainers Software University
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
PHP Basics Course Introduction SoftUni Team Technical Trainers Software University
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Advanced JavaScript Course Introduction SoftUni Team Technical Trainers Software University
PHP Workshop ‹#› PHP Error Handling. PHP Workshop ‹#› Types There are 12 unique error types, which can be grouped into 3 main categories: Informational.
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Design Patterns: Structural Design Patterns
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
Conditional Statements Implementing Control-Flow Logic in C# SoftUni Team Technical Trainers Software University
Composer packages Installing and Using Composer, Packagist, Packaging your code Mario Peshev Technical Trainer Software University
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
Database APIs and Wrappers
Svetlin Nakov Technical Trainer Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Defensive Programming, Assertions and Exceptions Designing Fault-Resistant Code SoftUni Team Technical Trainers Software University
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University
Static Members and Namespaces Static Members, Indexers, Operators, Namespaces SoftUni Team Technical Trainers Software University
JavaScript Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Templating, Routing, lodash Extending functionality using Collections SoftUni Team Technical Trainers Software University
Controllers and Markup Controllers, $scope, Markup, Directives, Expressions, Binding, Filters, Validation SoftUni Team Technical Trainers Software University.
AMD and RequireJS Splitting JavaScript Code into Dependent Modules Software University Technical Trainers SoftUni Team.
Using SQL Connecting, Retrieving Data, Executing SQL Commands, … Svetlin Nakov Technical Trainer Software University
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
C# Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Sessions and Cookies State Management, Cookies, Sessions, Hidden Fields SoftUni Team Technical Trainers Software University
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
PHP Error Handling Section :I Source: 1.
High-Quality Programming Code Code Correctness, Readability, Maintainability Svetlin Nakov Technical Trainer Software University
High-Quality Code: Course Introduction Course Introduction SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
8 th Semester, Batch 2008 Department Of Computer Science SSUET.
Advanced C# Course Introduction SoftUni Team Technical Trainers Software University
Prototype Chain and Inheritance Prototype chain, Inheritance, Accessing Base Members Software University Technical Trainers SoftUni Team.
Events Event Handling in JavaScript SoftUni Team Technical Trainers Software University
Reflection Programming under the hood SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Operators and Expressions
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
Martin Kruliš Who is General Failure and why is he reading my disk? by Martin Kruliš (v1.0)1.
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Programming for Beginners Course Introduction SoftUni Team Technical Trainers Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
PHP Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Programming Fundamentals Course Introduction SoftUni Team Technical Trainers Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
ASP.NET MVC Course Program, Trainers, Evaluation, Exams, Resources SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
Repeating Code Multiple Times
Extending functionality using Collections
Presentation transcript:

PHP Exception Handling How to handle and create user-defined exceptions Mario Peshev Technical Trainer Software University try { // some code that may fail } catch (Exception $e) { echo 'This code failed'; }

Table of Contents 1.Try-catch Construct 2.The Exception Class 3.Throwing Exceptions 4.Creating Custom Exceptions 5.Global Exception Handlers 6.Die Function 7.Setting the Level of Output Operator 2

3  Exceptions are used to change the normal flow of a script if a specified error occurs.  Exceptions are error messages that:  Allow part of application to notify the rest that there is a problem.  Are used when the error does not allow the application or part of it to continue execution. Introduction to Exceptions

4  PHP doesn't throw any exceptions by default  Example: division by zero produces only warning  The program continues execution and presents incorrect result  However PHP provides inbuilt engine for handling errors and warnings and turning them in exceptions Exception  PHP incorporates the Exception class to handle exceptions PHP Exceptions

Error Reporting Level  PHP has many levels of errors and warnings  You can configure which are printed to the browser or the log files  The error reporting level is integer representing bit fields  Can be defined as Boolean operations between constants 5

6  E_ERROR (level 1) – Fatal run-time errors. Errors that can not be recovered from. Execution of the script is halted;  E_WARNING (level 2) – Non-fatal run-time errors. Execution of the script is not halted;  E_NOTICE (level 8) – Run-time notices. The script found something that might be an error or might not; Level Examples

7  E_STRICT (level 2048) – Run-time notices. PHP suggest changes to your code to help interoperability and compatibility of the code;  E_RECOVERABLE_ERROR (level 4096) – Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle;  E_ALL (level 8192) – All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0); Level Examples

Error Reporting Level  Error reporting level can be set in the php.ini or at runtime with the error_reporting function  Takes one parameter – the desired error level  E_ALL & ~E_NOTICE means all errors except those of level " E_NOTICE "  This is the default level 8 error_reporting(E_ALL & ~E_NOTICE);

Catching an Exception  Exceptions can be caught and some code executed  Exception, raised in the try block is caught (catched)  Each try block must have at least one catch block  Different catch blocks may correspond to different classes of exceptions  In this example the catch block will intercept all types of exceptions 9 try { // some code that may fail } catch (Exception $e) { echo 'This code failed'; }

Catching an Exception - Example 10 $a = 5; $b = 0; try { if ($b == 0) { throw new Exception("You cannot divide by zero"); } else { $i = $a/$b; echo $i; } } catch (Exception $e) { echo $e->getMessage(); }

Catching Exceptions  The exceptions, matched by a catch block, are stopped  The rest of the application continues working  Exceptions can be re-thrown  If exception is not caught, a PHP Fatal Error is issued and execution stops  When exception is raised in a try block, the rest of the block is not executed  Try-catch blocks can be nested 11

The Exception class  The Exception class has several useful methods  getMessage() – returns user friendly message, explaining the error  getCode() – returns integer code, usually specifying the error and is useful to distinguish exceptions  getFile(), getLine(), getCode() – return where the exception occurred  getTrace(), getTraceAsString() – return the trace data as array or string and is useful to log the data about the exceptions 12

The Exception class - Example  The methods provided by the Exception class can be used to notify the user. 13 function checkNum($number) { if($number>1) { if($number>1) { throw new Exception("Value must be 1 or below", 999); throw new Exception("Value must be 1 or below", 999);} return true; } try { checkNum(2); } catch (Exception $e) { echo $e->getMessage()." "." code: ".$e->getCode(); }

Creating Custom Exceptions  Creating custom exception is as simple as creating object of class Exception  Creating object of class exception does not mean it is thrown  Constructor has two parameters – message and optional error code  Exceptions are thrown with the throw operator throw new Exception("Value must be 1 or below", 999); throw new Exception("You cannot divide by zero"); 8

Throwing Multiple Exceptions - Example try { if (!$_POST['name']) if (!$_POST['name']) throw new Exception('No name supplied', 1001); throw new Exception('No name supplied', 1001); if (!$_POST[' ']) if (!$_POST[' ']) throw new Exception ('No supplied', 1002); throw new Exception ('No supplied', 1002); if (!mysql_query("insert into sometable values ('".$_POST['name']."', '".$_POST[' ']."'")) if (!mysql_query("insert into sometable values ('".$_POST['name']."', '".$_POST[' ']."'")) throw new Exception ('Unable to save!', 1003); throw new Exception ('Unable to save!', 1003); } catch (Exception $e) { $code = $e->getCode(); $code = $e->getCode(); if ($code > 1000 && $code 1000 && $code < 1003) echo "Please fill in all the data"; echo "Please fill in all the data"; elseif ($code == 1004) elseif ($code == 1004) echo "Database error or unescaped symbols!"; echo "Database error or unescaped symbols!"; else { else { throw $e; // re-throw the exception! throw $e; // re-throw the exception! }} 9

Extending the Exception class  Extending the Exception class is highly recommended  Allows usage of multiple catch blocks for different classes of exceptions, instead of distinguishing them by their code  Each exception class can have predefined error and code  No need to set when throwing, constructor may be without parameters  Methods of the class may contain more functionality 10

Exception Extending – Examples  Using extensions of the Exception class is no different than simply extending any other class class EMyException extends Exception { public function __construct() { public function __construct() { parent::__construct('Ooops!', 101); parent::__construct('Ooops!', 101); }} try { … Throw new EMyException(); Throw new EMyException(); } catch (EMyException $e) { echo "My exception was raised!"." "; echo "My exception was raised!"." "; echo $e->getMessage()." / code: ".$e->getCode(); echo $e->getMessage()." / code: ".$e->getCode();} 11

Exception Extending – Examples  Example with multiple catch blocks  Much better than having single catch with complex code to handle different types of exceptions 12 try { $a = 5; $b = 2; $i = $a/$b; throw new EMyException(); } catch (EMyException $e) { echo 'My exception was raised'; } catch (Exception $e) { echo 'You cannot divide by zero'; }

Global Exception Handlers  set_exception_handler($callback) – sets the function, specified by $callback as exception handler  All exceptions, not stopped by try…catch constructs are sent to this function function ex_handler ($exception) { echo "Uncaught: ".$exception->getMessage(); echo "Uncaught: ".$exception->getMessage();} set_exception_handler('ex_handler'); throw new Exception ('boom'); echo 'this line is not executed'; 13

Global Warnings Handler  Warnings are different from exceptions  They are recoverable – engine can continue execution  Different function for settings global handler  set_error_handler – similar to set_exception_handler  The callback function gets other parameters  Can be used to convert warnings into exceptions  Optional second parameter defines the level of errors caught 20

21  There are errors that cannot be caught with Exception class, set_exception_handler or set_error_handler ;  Parse errors  Fatal errors  Core errors  Example: calling a function that does not exist: Impossible to Catch Errors $a = 2; $b = 3; multiply_two(a,b);

die Function  The die function is commonly used alias of exit function  Stops execution of the program  Takes one optional parameter – string or integer status  If status is string, it is printed before exiting  Exiting with status 0 means program finished successfully  Any other status means error 22

die Function – Example  die is commonly used this way:  If mysql_connect fails, it returns false  PHP continues with execution of the next statement to evaluate the logical expression  If mysql_connect succeeds, PHP does not execute the other statement  The logical result will be true anyway  Same can be done with if  The " or " approach is inherited by Perl and many developers prefer it 23 mysql_connect(…) or die ('Unable to connect DB server');

operator  Expressions in PHP can be prefixed  Error control operator  If error occurs during operation execution, it is ignored  Can be used with function calls, variables, include calls, constants, etc.  Cannot be used with function and class definitions, conditional statements, etc. $res ('no_such_file') or die ('…'); $value $value / 0;

25 Operator

26  Try-catch Construct  The Exception Class  Throwing Exceptions  Creating Custom Exceptions  Global Exception Handlers  Die Function  Setting the Level of Output  Operator Summary

? ? ? ? ? ? ? ? ?

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 28  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA licenseFundamentals of Computer Programming with C#CC-BY-SA  "C# Part I" course by Telerik Academy under CC-BY-NC-SA licenseC# Part ICC-BY-NC-SA

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg