SlideShare a Scribd company logo
Error Management in PHP
Types of errors
Compile-time errors Errors detected by the parser while it is compiling
a script. Cannot be trapped from within the script itself.
Fatal errors Errors that halt the execution of a script. Cannot be trapped.
Recoverable errors Errors that represent significant failures, but can still be
handled in a safe way.
Warnings Recoverable errors that indicate a run-time fault. Do not halt
the execution of the script.
Notices Indicate that an error condition occurred, but is not
necessarily significant. Do not halt the execution of the script.
Error Reporting
• By default, PHP reports any errors it encounters to the script’s
output unless you control it as follows
1. Configuring Php.ini
2. Handling Errors by setting set_error_handler()
1. Configuring Php.ini
– Several configuration directives in the php.ini file allow you to fine tune
how—and which—errors are reported.
– error_reporting,
– display_errors
– log_errors.
You can find these in php.ini file
1. Configuring Php.ini
• error_reporting
– determines which errors are reported by PHP
– Eg: error_reporting=E_ALL & ~E_NOTICE
• display_errors
– if turned on, errors are outputted to the script’s output; this is not
desirable in a production environment, as everyone will be able to see
your scripts’ errors. Eg: display_errors = ON
• log_errors,
– which causes errors to be written to your web server’s error log, so that
only developers can utilise it and end users will not be informed of same
– Eg:log_errors,=ON
2. Handling Errors
• The set_error_handler() function sets a user-defined function to
handle errors.
• Eg: set_error_handler(error_function,error_types)
<?php
//error handler function
function customError($errno, $errstr, $errfile,
$errline)
{
echo "<b>Custom error:</b> [$errno] $errstr<br
/>";
echo " Error on line $errline in $errfile<br />";
echo "Ending Script";
die();
}
//set error handler
set_error_handler("customError");
$test=2;
//trigger error
if ($test>1)
{
trigger_error("A custom error has been
triggered");
}
Exception Handling in PHP
Exception Handling in PHP
• Exceptions provide an error control mechanism that is more fine-
grained than traditional PHP fault handling.There are several key
differences between “regular” PHP errors and exceptions:
• Exceptions are objects, created (or “thrown”) when an error occurs
• Exceptions can be handled at different points in a script’s execution, and
different types of exceptions can be handled by separate portions of a
script’s code
• All unhandled exceptions are fatal
• Exceptions can be thrown from the __construct method on failure
• Exceptions change the flow of the application
The Basic Exception Class
• As we mentioned in the previous paragraph, exceptions are objects
that must be direct or indirect (for example through inheritance)
instances of the Exception base class.
• The latter is built into PHP itself, and is declared as follows:
The Basic Exception Class
class Exception {
// The error message associated with this exception
protected $message = ’Unknown Exception’;
// The error code associated with this exception
protected $code = 0;
// The pathname of the file where the exception occurred
protected $file;
// The line of the file where the exception occurred
protected $line;
// Constructor
function __construct ($message = null, $code =
0);
// Returns the message
final function getMessage();
// Returns the error code
final function getCode();
// Returns the file name
final function getFile();
// Returns the file line
final function getLine();
// Returns an execution backtrace as an array
final function getTrace();
// Returns a backtrace as a string
final function getTraceAsString();
// Returns a string representation of the
exception
function __toString();
}
The Basic Exception Class
• Almost all of the properties of an Exception are automatically
filled in for you by the interpreter—generally speaking, you only
need to provide a message and a code, and all the remaining
information will be taken care of for you.
• Since Exception is a normal (if built-in) class, you can extend it
and effectively create your own exceptions, thus providing your
error handlers with any additional information that your
application requires.
Throwing Exceptions
• Exceptions are usually created and thrown when an error occurs by using
the throw construct:
if ($error) {
throw new Exception ("This is my error");
}
• Exceptions then “bubble up” until they are either handled by the script or
cause a fatal exception
• The handling of exceptions is performed using a try...catch block:
Example
try {
if ($error) {
throw new Exception ("This is my error");
}
} catch (Exception $e) {
echo $e->getMessage();
}
• In the example above, any exception that is thrown inside the try{} block is
going to be caught and passed on the code inside the catch{} block, where it
can be handled
Lazy Loading
Lazy Loading
• Prior to PHP 5, if you try to create an object on an undefined class(perhaps
that class is written on another file which you forgot to include) would
cause a fatal error.
• This meant that you needed to include all of the class files that you might
need, rather than loading them as they were needed
• To solve this problem, PHP 5 features an “autoload” facility that makes it
possible to implement “lazy loading”, or loading of classes on-demand only
• When we try to create an object of undefined class PHP will try to call the
__autoload() global magic function so that the script may be given an
opportunity to load it.
__autoload() - Example
function __autoload($class)
{
// Require PEAR-compatible classes
require_once(“$class.php”)
}
$obj = new SomeClass();
__autoload() - Example
function __autoload($class)
{
// Require PEAR-compatible classes
require_once(“$class.php”)
}
$obj = new SomeClass();
You tried to create an object of
SomeClass. But you forgot that someClass
is defined in another page called
SomeClass.php
__autoload() - Example
function __autoload($class)
{
// Require PEAR-compatible classes
require_once(“$class.php”)
}
$obj = new SomeClass();
When you tried to do so, PHP will
automatically calls __autoload() which
will have an argument ie the class name
for which object we tried to create
__autoload() - Example
function __autoload($class)
{
// Require PEAR-compatible classes
require_once(“$class.php”)
}
$obj = new SomeClass();
We are including the file called
“someClass.php”
The advantage of lazy loading is that we can include files upon its requirement only
rather than including all the files unnecessarily
Questions?
“A good question deserve a good grade…”
End of day
Contact Us
Emarald Mall (Big Bazar Building)
Mavoor Road, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
NC Complex, Near Bus Stand
Mukkam, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
Start up Village
Eranakulam,
Kerala, India.
Email: info@baabtra.com
If this presentation helped you, please visit our
page facebook.com/baabtra and like it.
Thanks in advance.
www.baabtra.com | www.massbaab.com |www.baabte.com
Ad

Recommended

Handling error & exception in php
Handling error & exception in php
Pravasini Sahoo
 
Php Error Handling
Php Error Handling
mussawir20
 
Php exceptions
Php exceptions
Damian Sromek
 
PHP - Introduction to PHP Error Handling
PHP - Introduction to PHP Error Handling
Vibrant Technologies & Computers
 
Error reporting in php
Error reporting in php
Mudasir Syed
 
Errors, Exceptions & Logging (PHP Hants Oct '13)
Errors, Exceptions & Logging (PHP Hants Oct '13)
James Titcumb
 
Elegant Ways of Handling PHP Errors and Exceptions
Elegant Ways of Handling PHP Errors and Exceptions
ZendCon
 
Types of Error in PHP
Types of Error in PHP
Vineet Kumar Saini
 
Exceptions in PHP
Exceptions in PHP
JanTvrdik
 
Surprise! It's PHP :) (unabridged)
Surprise! It's PHP :) (unabridged)
Sharon Levy
 
PHP - Introduction to PHP - Mazenet Solution
PHP - Introduction to PHP - Mazenet Solution
Mazenetsolution
 
Perl exceptions lightning talk
Perl exceptions lightning talk
Peter Edwards
 
Php(report)
Php(report)
Yhannah
 
Methods of debugging - Atomate.net
Methods of debugging - Atomate.net
Vitalie Chiperi
 
Lesson 4 constant
Lesson 4 constant
MLG College of Learning, Inc
 
Decision Structures
Decision Structures
primeteacher32
 
Bioinformatica 27-10-2011-p4-files
Bioinformatica 27-10-2011-p4-files
Prof. Wim Van Criekinge
 
Basic of PHP
Basic of PHP
Nisa Soomro
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception Handling
P3 InfoTech Solutions Pvt. Ltd.
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
wahidullah mudaser
 
Debugging With Php
Debugging With Php
Automatem Ltd
 
Php tutorial
Php tutorial
S Bharadwaj
 
PHP 5.3
PHP 5.3
Chris Stone
 
Exception handling in ASP .NET
Exception handling in ASP .NET
baabtra.com - No. 1 supplier of quality freshers
 
Introduction to PHP
Introduction to PHP
Jussi Pohjolainen
 
Beginners PHP Tutorial
Beginners PHP Tutorial
alexjones89
 
Error and Exception Handling in PHP
Error and Exception Handling in PHP
Arafat Hossan
 
Php introduction and configuration
Php introduction and configuration
Vijay Kumar Verma
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
Jalpesh Vasa
 
Error Handling In PHP with all Try catch anf various runtime errors
Error Handling In PHP with all Try catch anf various runtime errors
PraveenHegde20
 

More Related Content

What's hot (20)

Exceptions in PHP
Exceptions in PHP
JanTvrdik
 
Surprise! It's PHP :) (unabridged)
Surprise! It's PHP :) (unabridged)
Sharon Levy
 
PHP - Introduction to PHP - Mazenet Solution
PHP - Introduction to PHP - Mazenet Solution
Mazenetsolution
 
Perl exceptions lightning talk
Perl exceptions lightning talk
Peter Edwards
 
Php(report)
Php(report)
Yhannah
 
Methods of debugging - Atomate.net
Methods of debugging - Atomate.net
Vitalie Chiperi
 
Lesson 4 constant
Lesson 4 constant
MLG College of Learning, Inc
 
Decision Structures
Decision Structures
primeteacher32
 
Bioinformatica 27-10-2011-p4-files
Bioinformatica 27-10-2011-p4-files
Prof. Wim Van Criekinge
 
Basic of PHP
Basic of PHP
Nisa Soomro
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception Handling
P3 InfoTech Solutions Pvt. Ltd.
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
wahidullah mudaser
 
Debugging With Php
Debugging With Php
Automatem Ltd
 
Php tutorial
Php tutorial
S Bharadwaj
 
PHP 5.3
PHP 5.3
Chris Stone
 
Exception handling in ASP .NET
Exception handling in ASP .NET
baabtra.com - No. 1 supplier of quality freshers
 
Introduction to PHP
Introduction to PHP
Jussi Pohjolainen
 
Beginners PHP Tutorial
Beginners PHP Tutorial
alexjones89
 
Error and Exception Handling in PHP
Error and Exception Handling in PHP
Arafat Hossan
 
Php introduction and configuration
Php introduction and configuration
Vijay Kumar Verma
 

Similar to Introduction to php exception and error management (20)

Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
Jalpesh Vasa
 
Error Handling In PHP with all Try catch anf various runtime errors
Error Handling In PHP with all Try catch anf various runtime errors
PraveenHegde20
 
lecture 15.pptx
lecture 15.pptx
ITNet
 
object oriented programming in PHP & Functions
object oriented programming in PHP & Functions
BackiyalakshmiVenkat
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
rICh morrow
 
Exception handling with python class 12.pptx
Exception handling with python class 12.pptx
PreeTVithule1
 
ASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation Controls
Randy Connolly
 
Py-Slides-9.ppt
Py-Slides-9.ppt
wulanpermatasari27
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Muhamad Al Imran
 
Php i basic chapter 3
Php i basic chapter 3
Muhamad Al Imran
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Muhamad Al Imran
 
Introduction to php basics
Introduction to php basics
baabtra.com - No. 1 supplier of quality freshers
 
PHP-03-Functions.ppt
PHP-03-Functions.ppt
Jamers2
 
PHP-03-Functions.ppt
PHP-03-Functions.ppt
ShishirKantSingh1
 
Basics PHP
Basics PHP
Alokin Software Pvt Ltd
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
anshkhurana01
 
PHP - Introduction to PHP Functions
PHP - Introduction to PHP Functions
Vibrant Technologies & Computers
 
Php
Php
ksujitha
 
Exception handling.pptxnn h
Exception handling.pptxnn h
sabarivelan111007
 
Sourcerer and Joomla! rev. 20130903
Sourcerer and Joomla! rev. 20130903
DouglasPickett
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
Jalpesh Vasa
 
Error Handling In PHP with all Try catch anf various runtime errors
Error Handling In PHP with all Try catch anf various runtime errors
PraveenHegde20
 
lecture 15.pptx
lecture 15.pptx
ITNet
 
object oriented programming in PHP & Functions
object oriented programming in PHP & Functions
BackiyalakshmiVenkat
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
rICh morrow
 
Exception handling with python class 12.pptx
Exception handling with python class 12.pptx
PreeTVithule1
 
ASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation Controls
Randy Connolly
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Muhamad Al Imran
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Muhamad Al Imran
 
PHP-03-Functions.ppt
PHP-03-Functions.ppt
Jamers2
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
anshkhurana01
 
Sourcerer and Joomla! rev. 20130903
Sourcerer and Joomla! rev. 20130903
DouglasPickett
 
Ad

More from baabtra.com - No. 1 supplier of quality freshers (20)

Agile methodology and scrum development
Agile methodology and scrum development
baabtra.com - No. 1 supplier of quality freshers
 
Best coding practices
Best coding practices
baabtra.com - No. 1 supplier of quality freshers
 
Core java - baabtra
Core java - baabtra
baabtra.com - No. 1 supplier of quality freshers
 
Acquiring new skills what you should know
Acquiring new skills what you should know
baabtra.com - No. 1 supplier of quality freshers
 
Baabtra.com programming at school
Baabtra.com programming at school
baabtra.com - No. 1 supplier of quality freshers
 
99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love
baabtra.com - No. 1 supplier of quality freshers
 
Php sessions & cookies
Php sessions & cookies
baabtra.com - No. 1 supplier of quality freshers
 
Php database connectivity
Php database connectivity
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 6 database normalisation
Chapter 6 database normalisation
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 5 transactions and dcl statements
Chapter 5 transactions and dcl statements
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 4 functions, views, indexing
Chapter 4 functions, views, indexing
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 3 stored procedures
Chapter 3 stored procedures
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Microsoft holo lens
Microsoft holo lens
baabtra.com - No. 1 supplier of quality freshers
 
Blue brain
Blue brain
baabtra.com - No. 1 supplier of quality freshers
 
5g
5g
baabtra.com - No. 1 supplier of quality freshers
 
Aptitude skills baabtra
Aptitude skills baabtra
baabtra.com - No. 1 supplier of quality freshers
 
Gd baabtra
Gd baabtra
baabtra.com - No. 1 supplier of quality freshers
 
Ad

Recently uploaded (20)

"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
"Scaling in space and time with Temporal", Andriy Lupa.pdf
"Scaling in space and time with Temporal", Andriy Lupa.pdf
Fwdays
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
"Scaling in space and time with Temporal", Andriy Lupa.pdf
"Scaling in space and time with Temporal", Andriy Lupa.pdf
Fwdays
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 

Introduction to php exception and error management

  • 2. Types of errors Compile-time errors Errors detected by the parser while it is compiling a script. Cannot be trapped from within the script itself. Fatal errors Errors that halt the execution of a script. Cannot be trapped. Recoverable errors Errors that represent significant failures, but can still be handled in a safe way. Warnings Recoverable errors that indicate a run-time fault. Do not halt the execution of the script. Notices Indicate that an error condition occurred, but is not necessarily significant. Do not halt the execution of the script.
  • 3. Error Reporting • By default, PHP reports any errors it encounters to the script’s output unless you control it as follows 1. Configuring Php.ini 2. Handling Errors by setting set_error_handler()
  • 4. 1. Configuring Php.ini – Several configuration directives in the php.ini file allow you to fine tune how—and which—errors are reported. – error_reporting, – display_errors – log_errors. You can find these in php.ini file
  • 5. 1. Configuring Php.ini • error_reporting – determines which errors are reported by PHP – Eg: error_reporting=E_ALL & ~E_NOTICE • display_errors – if turned on, errors are outputted to the script’s output; this is not desirable in a production environment, as everyone will be able to see your scripts’ errors. Eg: display_errors = ON • log_errors, – which causes errors to be written to your web server’s error log, so that only developers can utilise it and end users will not be informed of same – Eg:log_errors,=ON
  • 6. 2. Handling Errors • The set_error_handler() function sets a user-defined function to handle errors. • Eg: set_error_handler(error_function,error_types) <?php //error handler function function customError($errno, $errstr, $errfile, $errline) { echo "<b>Custom error:</b> [$errno] $errstr<br />"; echo " Error on line $errline in $errfile<br />"; echo "Ending Script"; die(); } //set error handler set_error_handler("customError"); $test=2; //trigger error if ($test>1) { trigger_error("A custom error has been triggered"); }
  • 8. Exception Handling in PHP • Exceptions provide an error control mechanism that is more fine- grained than traditional PHP fault handling.There are several key differences between “regular” PHP errors and exceptions: • Exceptions are objects, created (or “thrown”) when an error occurs • Exceptions can be handled at different points in a script’s execution, and different types of exceptions can be handled by separate portions of a script’s code • All unhandled exceptions are fatal • Exceptions can be thrown from the __construct method on failure • Exceptions change the flow of the application
  • 9. The Basic Exception Class • As we mentioned in the previous paragraph, exceptions are objects that must be direct or indirect (for example through inheritance) instances of the Exception base class. • The latter is built into PHP itself, and is declared as follows:
  • 10. The Basic Exception Class class Exception { // The error message associated with this exception protected $message = ’Unknown Exception’; // The error code associated with this exception protected $code = 0; // The pathname of the file where the exception occurred protected $file; // The line of the file where the exception occurred protected $line; // Constructor function __construct ($message = null, $code = 0); // Returns the message final function getMessage(); // Returns the error code final function getCode(); // Returns the file name final function getFile(); // Returns the file line final function getLine(); // Returns an execution backtrace as an array final function getTrace(); // Returns a backtrace as a string final function getTraceAsString(); // Returns a string representation of the exception function __toString(); }
  • 11. The Basic Exception Class • Almost all of the properties of an Exception are automatically filled in for you by the interpreter—generally speaking, you only need to provide a message and a code, and all the remaining information will be taken care of for you. • Since Exception is a normal (if built-in) class, you can extend it and effectively create your own exceptions, thus providing your error handlers with any additional information that your application requires.
  • 12. Throwing Exceptions • Exceptions are usually created and thrown when an error occurs by using the throw construct: if ($error) { throw new Exception ("This is my error"); } • Exceptions then “bubble up” until they are either handled by the script or cause a fatal exception • The handling of exceptions is performed using a try...catch block:
  • 13. Example try { if ($error) { throw new Exception ("This is my error"); } } catch (Exception $e) { echo $e->getMessage(); } • In the example above, any exception that is thrown inside the try{} block is going to be caught and passed on the code inside the catch{} block, where it can be handled
  • 15. Lazy Loading • Prior to PHP 5, if you try to create an object on an undefined class(perhaps that class is written on another file which you forgot to include) would cause a fatal error. • This meant that you needed to include all of the class files that you might need, rather than loading them as they were needed • To solve this problem, PHP 5 features an “autoload” facility that makes it possible to implement “lazy loading”, or loading of classes on-demand only • When we try to create an object of undefined class PHP will try to call the __autoload() global magic function so that the script may be given an opportunity to load it.
  • 16. __autoload() - Example function __autoload($class) { // Require PEAR-compatible classes require_once(“$class.php”) } $obj = new SomeClass();
  • 17. __autoload() - Example function __autoload($class) { // Require PEAR-compatible classes require_once(“$class.php”) } $obj = new SomeClass(); You tried to create an object of SomeClass. But you forgot that someClass is defined in another page called SomeClass.php
  • 18. __autoload() - Example function __autoload($class) { // Require PEAR-compatible classes require_once(“$class.php”) } $obj = new SomeClass(); When you tried to do so, PHP will automatically calls __autoload() which will have an argument ie the class name for which object we tried to create
  • 19. __autoload() - Example function __autoload($class) { // Require PEAR-compatible classes require_once(“$class.php”) } $obj = new SomeClass(); We are including the file called “someClass.php” The advantage of lazy loading is that we can include files upon its requirement only rather than including all the files unnecessarily
  • 20. Questions? “A good question deserve a good grade…”
  • 22. Contact Us Emarald Mall (Big Bazar Building) Mavoor Road, Kozhikode, Kerala, India. Ph: + 91 – 495 40 25 550 NC Complex, Near Bus Stand Mukkam, Kozhikode, Kerala, India. Ph: + 91 – 495 40 25 550 Start up Village Eranakulam, Kerala, India. Email: [email protected]
  • 23. If this presentation helped you, please visit our page facebook.com/baabtra and like it. Thanks in advance. www.baabtra.com | www.massbaab.com |www.baabte.com