Throwing and Catching Exceptions Tran Anh Tuan Edit from Telerik Software Academy

Slides:



Advertisements
Similar presentations
Windows Basic and Dynamic Disk Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator Marian Marinov CEO of 1H Ltd.
Advertisements

HTML Forms, GET, POST Methods Tran Anh Tuan Edit from Telerik Academy
Make swiftly iOS development Telerik Academy Telerik Academy Plus.
Amazon S 3, App Engine Blobstore, Google Cloud Storage, Azure Blobs Svetlin Nakov Telerik Software Academy academy.telerik.com.
RPN and Shunting-yard algorithm Ivaylo Kenov Telerik Software Academy academy.telerik.com Technical Assistant
Shortest paths in edge-weighted digraph Krasin Georgiev Technical University of Sofia g.krasin at gmail com Assistant Professor.
Telerik Software Academy Telerik School Academy.
Asynchronous Programming with C# and WinRT
Unleash the Power of JavaScript Tooling Telerik Software Academy End-to-end JavaScript Applications.
Touch and Gestures with Xamarin Forms
Character sequences, C-strings and the C++ String class, Working with Strings Learning & Development Team Telerik Software Academy.
Hybrid or Native?! Doncho Minkov Telerik Software Academy Senior Technical Trainer
Done already for your convenience! Telerik School Academy Unity 2D Game Development.
Processing Sequences of Elements Telerik School Academy C# Fundamentals – Part 1.
With Mocha and Karma Telerik Academy Telerik Software Academy.
C# Fundamentals – Part I
Welcome to the JSON-stores world Telerik Software Academy Databases.
The Business Plan and the Business Model Margarita Antonova Volunteer Telerik Academy academy.telerik.com Business System Analyst Telerik Corporation.
What are ADTs, STL Intro, vector, list, queue, stack Learning & Development Team Telerik Software Academy.
Making JavaScript code by template! Learning & Development Team Telerik Software Academy.
Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training Who, What, Why?
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Web Applications in Hatch Tran Anh Tuan Edit from Telerik Academy
Processing Matrices and Multidimensional Tables Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Learning & Development Telerik Software Academy.
Reading and Writing Text Files Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Telerik Software Academy ASP.NET Web Forms.
Classical OOP in JavaScript Classes and stuff Telerik Software Academy
Optimization problems, Greedy Algorithms, Optimal Substructure and Greedy choice Learning & Development Team Telerik Software.
Using Selenium for Mobile Web Testing Powered by KendoUI Telerik QA Academy Atanas Georgiev Senior QA Engineer KendoUI Team.
NoSQL Concepts, Redis, MongoDB, CouchDB Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
New features: classes, generators, iterators, etc. Telerik Academy Plus JavaScript.Next.
Handling Errors during the Program Execution Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Loops, Conditional Statements, Functions Tran Anh Tuan Edit from Telerik Academy
Private/Public fields, Module, Revealing Module Learning & Development Team Telerik Software Academy.
Building Data-Driven ASP.NET Web Forms Apps Telerik Software Academy ASP.NET Web Forms.
Course Introduction Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Nikolay Kostov Telerik Software Academy Senior Software Developer and Trainer
Telerik Software Academy End-to-end JavaScript Applications.
What is a Database, MySQL Specifics Trần Anh Tuấn Edit from Telerik Software Academy
Planning and Tracking Software Quality Yordan Dimitrov Telerik Corporation Team Leader, Team Pulse, Team Leader, Team Pulse, Telerik Corporation,
What you need to know Ivaylo Kenov Telerik Corporation Telerik Academy Student.
Data binding concepts, Bindings in WinJS George Georgiev Telerik Software Academy academy.telerik.com Technical Trainer itgeorge.net.
Pavel Kolev Telerik Software Academy Senior.Net Developer and Trainer
Objects, Properties, Primitive and Reference Types Learning & Development Team Telerik Software Academy.
When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation Senior Developer and Team Leader.
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Doing the Canvas the "easy way"! Learning & Development Telerik Software Academy.
Creating and Running Your First C# Program Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Correctly Formatting the Source Code Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Data Types, Primitive Types in C++, Variables – Declaration, Initialization, Scope Telerik Software Academy academy.telerik.com Learning and Development.
The past, the present, the future Learning & Development Team Telerik Software Academy.
Learn to Design Error Steady Code Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
Processing Sequences of Elements Telerik Software Academy C# Fundamentals – Part 2.
Telerik JavaScript Framework Telerik Software Academy Hybrid Mobile Applications.
Telerik Software Academy Databases.
Things start to get serious Telerik Software Academy JavaScript OOP.
Learning & Development Mobile apps for iPhone & iPad.
Processing Matrices and Multidimensional Tables Telerik Software Academy C# Fundamentals – Part 2.
Nikolay Kostov Telerik Software Academy academy.telerik.com Team Lead, Senior Developer and Trainer
Functions and Function Expressions Closures, Function Scope, Nested Functions Telerik Software Academy
Implementing Control Logic in C# Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical trainer
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.
Inheritance, Abstraction, Encapsulation, Polymorphism Telerik Software Academy Mobile apps for iPhone & iPad.
Mocking tools for easier unit testing Telerik Software Academy High Quality Code.
What why and how? Telerik School Academy Unity 2D Game Development.
Windows Security Model Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator
Presentation transcript:

Throwing and Catching Exceptions Tran Anh Tuan Edit from Telerik Software Academy

 Try-catch construct  The Exception class  Throwing exceptions  Creating custom exceptions  Global exception handlers  die function  Setting the level of output  operator

 Exceptions are error messages  PHP provides inbuilt engine for handling errors  Allow part of application to notify the rest that there is a problem  Usually used when the error does not allow the application or part of it to continue execution  PHP also provides warnings  Similar to exceptions but allow the application to continue working

 PHP doesn't like to throw exceptions  Example: division by zero produces only warning  The program continues execution, even the result may be incorrect  Warnings can be converted in Exceptions

 Example of exception is division by zero  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 try { // some code that may fail } catch (Exception $e) { echo 'This code failed'; } try { // some code that may fail } catch (Exception $e) { echo 'This code failed'; }

 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

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

 The methods provided by the Exception class can be used to notify the user or log the error try { // some code that may fail // some code that may fail } catch (Exception $e) { $error_text = 'An error has occurred: '. $error_text = 'An error has occurred: '. $e->getMessage()." (code: ". $e->getMessage()." (code: ". $e->getCode().")"; $e->getCode().")"; echo $error_text; echo $error_text; system ("echo ".$error_text. system ("echo ".$error_text. " >> /var/log/myerrors.log"); " >> /var/log/myerrors.log");} try { // some code that may fail // some code that may fail } catch (Exception $e) { $error_text = 'An error has occurred: '. $error_text = 'An error has occurred: '. $e->getMessage()." (code: ". $e->getMessage()." (code: ". $e->getCode().")"; $e->getCode().")"; echo $error_text; echo $error_text; system ("echo ".$error_text. system ("echo ".$error_text. " >> /var/log/myerrors.log"); " >> /var/log/myerrors.log");}

 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 new Exception ('Something went wrong', 7); throw new Exception('Oops!');

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! }} 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! }}

 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

 Using extensions of the Exception class is no different than simply extending any other class class EMyException extends Exception { public function __construct() { parent::__construct('Ooops!', 101); }} try { … } catch (EMyException $e) { echo "My exception was raised!"; } class EMyException extends Exception { public function __construct() { parent::__construct('Ooops!', 101); }} try { … } catch (EMyException $e) { echo "My exception was raised!"; }

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

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

 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

 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

 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 mysql_connect(…) or die ('Unable to connect DB server');

 PHP has many levels of errors  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  Levels are E_ERROR, E_WARNING, E_PARSE, E_NOTICE, E_ALL, E_STRICT, etc. – about 14 levels as of PHP 5.2.4

 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 error_reporting(E_ALL & ~E_NOTICE);

 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, $res ('no_such_file') or die ('…'); $value $value / $res ('no_such_file') or die ('…'); $value $value / 0;

форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране