SlideShare ist ein Scribd-Unternehmen logo
1 von 23
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Exceptions in PHP
Exceptions in PHPExceptions in PHP
Exceptions in PHP
 
Surprise! It's PHP :) (unabridged)
Surprise! It's PHP :) (unabridged)Surprise! It's PHP :) (unabridged)
Surprise! It's PHP :) (unabridged)
 
PHP - Introduction to PHP - Mazenet Solution
PHP - Introduction to PHP - Mazenet SolutionPHP - Introduction to PHP - Mazenet Solution
PHP - Introduction to PHP - Mazenet Solution
 
Perl exceptions lightning talk
Perl exceptions lightning talkPerl exceptions lightning talk
Perl exceptions lightning talk
 
Php(report)
Php(report)Php(report)
Php(report)
 
Methods of debugging - Atomate.net
Methods of debugging - Atomate.netMethods of debugging - Atomate.net
Methods of debugging - Atomate.net
 
Lesson 4 constant
Lesson 4  constantLesson 4  constant
Lesson 4 constant
 
Decision Structures
Decision StructuresDecision Structures
Decision Structures
 
Bioinformatica 27-10-2011-p4-files
Bioinformatica 27-10-2011-p4-filesBioinformatica 27-10-2011-p4-files
Bioinformatica 27-10-2011-p4-files
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception Handling
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
Debugging With Php
Debugging With PhpDebugging With Php
Debugging With Php
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
PHP 5.3
PHP 5.3PHP 5.3
PHP 5.3
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Beginners PHP Tutorial
Beginners PHP TutorialBeginners PHP Tutorial
Beginners PHP Tutorial
 
Error and Exception Handling in PHP
Error and Exception Handling in PHPError and Exception Handling in PHP
Error and Exception Handling in PHP
 
Php introduction and configuration
Php introduction and configurationPhp introduction and configuration
Php introduction and configuration
 

Ähnlich wie Introduction to php exception and error management

Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Jalpesh Vasa
 
lecture 15.pptx
lecture 15.pptxlecture 15.pptx
lecture 15.pptxITNet
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckrICh morrow
 
ASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation ControlsASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation ControlsRandy Connolly
 
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)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 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)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-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.pptJamers2
 
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...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. 20130903Sourcerer and Joomla! rev. 20130903
Sourcerer and Joomla! rev. 20130903DouglasPickett
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
"PHP from soup to nuts" -- lab exercises
"PHP from soup to nuts" -- lab exercises"PHP from soup to nuts" -- lab exercises
"PHP from soup to nuts" -- lab exercisesrICh morrow
 
php fundamental
php fundamentalphp fundamental
php fundamentalzalatarunk
 

Ähnlich wie Introduction to php exception and error management (20)

Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
 
lecture 15.pptx
lecture 15.pptxlecture 15.pptx
lecture 15.pptx
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
 
ASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation ControlsASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation Controls
 
Py-Slides-9.ppt
Py-Slides-9.pptPy-Slides-9.ppt
Py-Slides-9.ppt
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
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)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)
 
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)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)
 
Introduction to php basics
Introduction to php   basicsIntroduction to php   basics
Introduction to php basics
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
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...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...
 
PHP - Introduction to PHP Functions
PHP -  Introduction to PHP FunctionsPHP -  Introduction to PHP Functions
PHP - Introduction to PHP Functions
 
Php
PhpPhp
Php
 
Sourcerer and Joomla! rev. 20130903
Sourcerer and Joomla! rev. 20130903Sourcerer and Joomla! rev. 20130903
Sourcerer and Joomla! rev. 20130903
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
"PHP from soup to nuts" -- lab exercises
"PHP from soup to nuts" -- lab exercises"PHP from soup to nuts" -- lab exercises
"PHP from soup to nuts" -- lab exercises
 
Unit testing
Unit testingUnit testing
Unit testing
 
php fundamental
php fundamentalphp fundamental
php fundamental
 

Mehr von baabtra.com - No. 1 supplier of quality freshers

Mehr von baabtra.com - No. 1 supplier of quality freshers (20)

Agile methodology and scrum development
Agile methodology and scrum developmentAgile methodology and scrum development
Agile methodology and scrum development
 
Best coding practices
Best coding practicesBest coding practices
Best coding practices
 
Core java - baabtra
Core java - baabtraCore java - baabtra
Core java - baabtra
 
Acquiring new skills what you should know
Acquiring new skills   what you should knowAcquiring new skills   what you should know
Acquiring new skills what you should know
 
Baabtra.com programming at school
Baabtra.com programming at schoolBaabtra.com programming at school
Baabtra.com programming at school
 
99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love 99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Microsoft holo lens
Microsoft holo lensMicrosoft holo lens
Microsoft holo lens
 
Blue brain
Blue brainBlue brain
Blue brain
 
5g
5g5g
5g
 
Aptitude skills baabtra
Aptitude skills baabtraAptitude skills baabtra
Aptitude skills baabtra
 
Gd baabtra
Gd baabtraGd baabtra
Gd baabtra
 

Kürzlich hochgeladen

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 

Kürzlich hochgeladen (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

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: info@baabtra.com
  • 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