SlideShare a Scribd company logo
PHP Exception handler Throwing and catching exceptions is the good way to make sure your application doesn't do stuff it isn't supposed to do and leaving your application broken.
ISSUE ?? When you're working on a web application, this might not be your desired action because you don't want to let your visitor know your application is broken. Instead, you want to handle exceptions your own way, by bubbling exceptions upwards so you can manage exceptions in one place.
Bubbling exceptions ?? Bubbling exceptions means that you check in your code fragment for an exception (in your try statement) and throwing this upwards (in your catch statement).
Exmp. class MMMException extends Exception {} function sendMailers() { try { // send MMM Mailers } catch (MMMException $e) { throw new MMMException($e->getMessage()); log_message('error', 'Some happen.'); } return $this->xmlrpc->send_error_message('001', 'error'); }
So Finally ... You can create your exception handler method to handle each exception on it's own and perform a specific action. In this case you might want to log these exceptions, but when accessing databases, files or webservices you might want to send out an e-mail to the administrator or developers.
Wrapping it up ... Throwing a default ‘Exception’ is bad practice if you ever want to act on that specific error scenario. Without extending the Exception class you can only catch all or none. New exceptions can be thrown in catch blocks. That way it’s possible to prevent unexpected exception types to cross certain application design boundaries. Once class design involves abstract classes or interfaces it is wise to design exception structures as well and organize them in similar layers of abstraction.
Sample code Let's start right to see sample code to emulate exception (Everyone loves code, right?)
At any point where a developer needs to handle the possibility of an exception being thrown he needs to know:- What Exceptions can I expect? What Exceptions do I plan to catch?
The Basic Exception Let’s assume a XMLRPC-based web-service client class used to submit order-data to a supplier’s web-service. The web-service client throws an exception if required configuration parameters are missing. The actual XMLRPC Client object will be initialized when the first webservice method is called.
The Basic Exception try { $client->submitOrder($order); } catch (Exception $e) { // We need to act on this asap... $AppError->register_error($e); // Redirect to application error page $Redirect->error($e); }
The Basic Exception In case of a configuration error a redirect is performed to an application-error page. And (just an example) some mechanism is triggered that starts to bug a (or all) developers that there’s a problem that needs immediate attention.
Knowing what to catch class WsXMLRPC_ClientException extends Exception {} class WsXMLRPC_ClientConfigurationException extends WsXMLRPC_ClientException{} class WsXMLRPC_ClientConnectionException extends WsXMLRPC_ClientException{}
class WsXMLRPC_Client { // ... private function initXMLRPC_Client() { if (!is_null($this->XMLRPC_Client)) { return; } if (!$this->config->searchAgent) { throw new WsXMLRPC_ClientConfigurationException( 'Configuration error' ); } try { $this->XMLRPC_Client = new XMLRPC_Client( $this->config->searchAgent,  array('exceptions'=>1) ); } catch (XMLRPC_Fault $e) { throw new WsXMLRPC_ClientConnectionException( 'Cannot load SearchAgent: '.$this->config->searchAgent ); } } }
Sample Code ... $client = new WsXMLRPC_Client($config); try { $client->submitOrder($order); } catch (WsXMLRPC_ClientConnectionException $e) { // store the order in a queue to be processed later $Order->queue(); $Redirect->Page('OrderQueued', $order); } catch (Exception $e) { // Catch everything, also WsXMLRPC_ClientConfigurationException // We need to act on this asap... $AppError->register_error($e); // Redirect to application error page $Redirect->error($e); }
Exception in batch job  do { $retry = false; try { $bool = // return true if send mail  if ($bool === false) { throw new MailSendException(); } } catch (MailSendException $e) { if (Not found SMTP Detail) { echo "$mailerid SMTP Details" ."ERROR.\n"; } else { if (Connection timeout error) { echo "connection time out error" ."$mailerid.\n"; } else { echo "Unknown error attempting to access " ."$mailerid.\n"; } } $retry = true; } } while ($retry);
[email_address]

More Related Content

What's hot (20)

PPT
Exception handling
Prafull Johri
 
PPT
Exception handling
Iblesoft
 
PPT
Exception handling and templates
farhan amjad
 
PPTX
Exception Handling in C++
Deepak Tathe
 
PPT
e computer notes - Creating views
ecomputernotes
 
PPTX
C++ ala
Megha Patel
 
PPTX
Angular Mini-Challenges
Jose Mendez
 
PPTX
exception handling in cpp
gourav kottawar
 
PPTX
Form Validation
Graeme Smith
 
PPTX
Exception handling c++
Jayant Dalvi
 
PDF
Exception Handling in the C++ Constructor
Somenath Mukhopadhyay
 
PDF
Error handling in XPages
dominion
 
PPTX
Rethrowing exception- JAVA
Rajan Shah
 
PPTX
JAVA SWITCH STATEMENT
Rhythm Suiwal
 
PDF
Logical Expressions in C/C++. Mistakes Made by Professionals
PVS-Studio
 
PDF
Exception handling
Pranali Chaudhari
 
PPT
Exception handling
pooja kumari
 
PDF
Declarative presentations UIKonf
Nataliya Patsovska
 
KEY
Cramp websockets
Antônio Roberto Silva
 
PDF
Exceptions ref
. .
 
Exception handling
Prafull Johri
 
Exception handling
Iblesoft
 
Exception handling and templates
farhan amjad
 
Exception Handling in C++
Deepak Tathe
 
e computer notes - Creating views
ecomputernotes
 
C++ ala
Megha Patel
 
Angular Mini-Challenges
Jose Mendez
 
exception handling in cpp
gourav kottawar
 
Form Validation
Graeme Smith
 
Exception handling c++
Jayant Dalvi
 
Exception Handling in the C++ Constructor
Somenath Mukhopadhyay
 
Error handling in XPages
dominion
 
Rethrowing exception- JAVA
Rajan Shah
 
JAVA SWITCH STATEMENT
Rhythm Suiwal
 
Logical Expressions in C/C++. Mistakes Made by Professionals
PVS-Studio
 
Exception handling
Pranali Chaudhari
 
Exception handling
pooja kumari
 
Declarative presentations UIKonf
Nataliya Patsovska
 
Cramp websockets
Antônio Roberto Silva
 
Exceptions ref
. .
 

Viewers also liked (14)

PDF
Avangate transition to_saa_s_-_whitepaper
2Checkout
 
PPTX
Surf Pitch Deck
sarahcornwell
 
PPT
Social Networking Media
2Checkout
 
PPTX
Gesl rainbow plus 13 presentation
yunir
 
PDF
5 Software Niche Affiliate Success Stories
2Checkout
 
ODP
High Performance Web Sites
Ravi Raj
 
PPT
Web Performance Tips
Ravi Raj
 
PPT
Web application security
Ravi Raj
 
PPTX
Conversion Rate Optimization
2Checkout
 
PPT
Code Review
Ravi Raj
 
PPT
Is it time to start using HTML 5
Ravi Raj
 
PPT
Character Encoding issue with PHP
Ravi Raj
 
PPT
5 Guaranteed Methods to Increase Your Software Business’ Revenue
2Checkout
 
PPT
How PHP Works ?
Ravi Raj
 
Avangate transition to_saa_s_-_whitepaper
2Checkout
 
Surf Pitch Deck
sarahcornwell
 
Social Networking Media
2Checkout
 
Gesl rainbow plus 13 presentation
yunir
 
5 Software Niche Affiliate Success Stories
2Checkout
 
High Performance Web Sites
Ravi Raj
 
Web Performance Tips
Ravi Raj
 
Web application security
Ravi Raj
 
Conversion Rate Optimization
2Checkout
 
Code Review
Ravi Raj
 
Is it time to start using HTML 5
Ravi Raj
 
Character Encoding issue with PHP
Ravi Raj
 
5 Guaranteed Methods to Increase Your Software Business’ Revenue
2Checkout
 
How PHP Works ?
Ravi Raj
 
Ad

Similar to PHP Exception handler (20)

PDF
Php exceptions
Damian Sromek
 
PDF
Effective PHP. Part 6
Vasily Kartashov
 
PDF
Object Oriented PHP - PART-2
Jalpesh Vasa
 
PDF
Introduction to php exception and error management
baabtra.com - No. 1 supplier of quality freshers
 
PDF
Elegant Ways of Handling PHP Errors and Exceptions
ZendCon
 
PDF
Nikola Poša "Handling exceptional conditions with grace and style"
Fwdays
 
KEY
Code Fast, Die Young, Throw Structured Exceptions
John Anderson
 
PDF
Dealing with not so exceptional exceptions
Charles Desneuf
 
PPTX
object oriented programming in PHP & Functions
BackiyalakshmiVenkat
 
PDF
TDC 2015 - POA - Trilha PHP - Shit Happens
Jackson F. de A. Mafra
 
PDF
Zend VMにおける例外の実装
Yoshio Hanawa
 
KEY
Code Fast, die() Early, Throw Structured Exceptions
John Anderson
 
PDF
Les exceptions, oui, mais pas n'importe comment
Charles Desneuf
 
PDF
Zend VMにおける例外の実装
Yoshio Hanawa
 
PPT
Exceptions irst
jkumaranc
 
PPTX
Coding for Scale and Sanity
JimKellerES
 
PDF
Exception Handling: Designing Robust Software in Ruby (with presentation note)
Wen-Tien Chang
 
PDF
Exceptions in PHP
JanTvrdik
 
PPTX
Training material exceptions v1
Shinu Suresh
 
Php exceptions
Damian Sromek
 
Effective PHP. Part 6
Vasily Kartashov
 
Object Oriented PHP - PART-2
Jalpesh Vasa
 
Introduction to php exception and error management
baabtra.com - No. 1 supplier of quality freshers
 
Elegant Ways of Handling PHP Errors and Exceptions
ZendCon
 
Nikola Poša "Handling exceptional conditions with grace and style"
Fwdays
 
Code Fast, Die Young, Throw Structured Exceptions
John Anderson
 
Dealing with not so exceptional exceptions
Charles Desneuf
 
object oriented programming in PHP & Functions
BackiyalakshmiVenkat
 
TDC 2015 - POA - Trilha PHP - Shit Happens
Jackson F. de A. Mafra
 
Zend VMにおける例外の実装
Yoshio Hanawa
 
Code Fast, die() Early, Throw Structured Exceptions
John Anderson
 
Les exceptions, oui, mais pas n'importe comment
Charles Desneuf
 
Zend VMにおける例外の実装
Yoshio Hanawa
 
Exceptions irst
jkumaranc
 
Coding for Scale and Sanity
JimKellerES
 
Exception Handling: Designing Robust Software in Ruby (with presentation note)
Wen-Tien Chang
 
Exceptions in PHP
JanTvrdik
 
Training material exceptions v1
Shinu Suresh
 
Ad

Recently uploaded (20)

PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 

PHP Exception handler

  • 1. PHP Exception handler Throwing and catching exceptions is the good way to make sure your application doesn't do stuff it isn't supposed to do and leaving your application broken.
  • 2. ISSUE ?? When you're working on a web application, this might not be your desired action because you don't want to let your visitor know your application is broken. Instead, you want to handle exceptions your own way, by bubbling exceptions upwards so you can manage exceptions in one place.
  • 3. Bubbling exceptions ?? Bubbling exceptions means that you check in your code fragment for an exception (in your try statement) and throwing this upwards (in your catch statement).
  • 4. Exmp. class MMMException extends Exception {} function sendMailers() { try { // send MMM Mailers } catch (MMMException $e) { throw new MMMException($e->getMessage()); log_message('error', 'Some happen.'); } return $this->xmlrpc->send_error_message('001', 'error'); }
  • 5. So Finally ... You can create your exception handler method to handle each exception on it's own and perform a specific action. In this case you might want to log these exceptions, but when accessing databases, files or webservices you might want to send out an e-mail to the administrator or developers.
  • 6. Wrapping it up ... Throwing a default ‘Exception’ is bad practice if you ever want to act on that specific error scenario. Without extending the Exception class you can only catch all or none. New exceptions can be thrown in catch blocks. That way it’s possible to prevent unexpected exception types to cross certain application design boundaries. Once class design involves abstract classes or interfaces it is wise to design exception structures as well and organize them in similar layers of abstraction.
  • 7. Sample code Let's start right to see sample code to emulate exception (Everyone loves code, right?)
  • 8. At any point where a developer needs to handle the possibility of an exception being thrown he needs to know:- What Exceptions can I expect? What Exceptions do I plan to catch?
  • 9. The Basic Exception Let’s assume a XMLRPC-based web-service client class used to submit order-data to a supplier’s web-service. The web-service client throws an exception if required configuration parameters are missing. The actual XMLRPC Client object will be initialized when the first webservice method is called.
  • 10. The Basic Exception try { $client->submitOrder($order); } catch (Exception $e) { // We need to act on this asap... $AppError->register_error($e); // Redirect to application error page $Redirect->error($e); }
  • 11. The Basic Exception In case of a configuration error a redirect is performed to an application-error page. And (just an example) some mechanism is triggered that starts to bug a (or all) developers that there’s a problem that needs immediate attention.
  • 12. Knowing what to catch class WsXMLRPC_ClientException extends Exception {} class WsXMLRPC_ClientConfigurationException extends WsXMLRPC_ClientException{} class WsXMLRPC_ClientConnectionException extends WsXMLRPC_ClientException{}
  • 13. class WsXMLRPC_Client { // ... private function initXMLRPC_Client() { if (!is_null($this->XMLRPC_Client)) { return; } if (!$this->config->searchAgent) { throw new WsXMLRPC_ClientConfigurationException( 'Configuration error' ); } try { $this->XMLRPC_Client = new XMLRPC_Client( $this->config->searchAgent, array('exceptions'=>1) ); } catch (XMLRPC_Fault $e) { throw new WsXMLRPC_ClientConnectionException( 'Cannot load SearchAgent: '.$this->config->searchAgent ); } } }
  • 14. Sample Code ... $client = new WsXMLRPC_Client($config); try { $client->submitOrder($order); } catch (WsXMLRPC_ClientConnectionException $e) { // store the order in a queue to be processed later $Order->queue(); $Redirect->Page('OrderQueued', $order); } catch (Exception $e) { // Catch everything, also WsXMLRPC_ClientConfigurationException // We need to act on this asap... $AppError->register_error($e); // Redirect to application error page $Redirect->error($e); }
  • 15. Exception in batch job do { $retry = false; try { $bool = // return true if send mail if ($bool === false) { throw new MailSendException(); } } catch (MailSendException $e) { if (Not found SMTP Detail) { echo "$mailerid SMTP Details" ."ERROR.\n"; } else { if (Connection timeout error) { echo "connection time out error" ."$mailerid.\n"; } else { echo "Unknown error attempting to access " ."$mailerid.\n"; } } $retry = true; } } while ($retry);