SlideShare a Scribd company logo
PHP Exceptions tips
How to use exceptions properly?

       Damian Sromek
       damiansromek.pl
          2012-05
What's an exception?
Software can not finish task by performing
regular scenario and you should not ignore it.

● External system does not work
  eg. database, network, filesystem
● Software is used/configured wrong
  eg. credentials not set
● There's a bug in software
  eg. somehow program came to invalid state,
  object was requested to do something inappropriate / "stupid"
What's NOT an exception?
Software can not finish a task but you know it's
nothing strange when some criteria are not
met.

● Validator failure
   eg. wrong form field value, wrong credentials when logging in

Database access methods

● findByPK - should return "null" if no unique
  result
● findAll - should return empty collection if no
  results
Main types of exceptions
● LogicException
  Software got to wrong state but it will not
  happen again when programmer fixes the
  code
  eg. filling missing configuration, better form validation


● RuntimeException
  Software got to wrong state because of
  external dependency that could not have
  been avoided any way
  eg. network error, database failure
PHP spl exceptions
http://php.net/manual/en/language.exceptions.php
http://www.php.net/manual/en/spl.exceptions.php
Sadly there's not much about exceptions in PHP documentation.


http://www.php.net/~helly/php/ext/spl/classException.html
Exception
  LogicException
     BadFunctionCallException
       BadMethodCallException
     DomainException
     InvalidArgumentException
     LengthException
     OutOfRangeException
  RuntimeException
     OutOfBoundsException
     OverflowException
     RangeException
     UnderflowException
     UnexpectedValueException
Exceptions instead of PHP errors
Convert PHP errors to exception to get better
control over your software
http://www.php.net/manual/en/class.errorexception.php
<?php
function exception_error_handler ($errno, $errstr, $errfile , $errline ) {
    throw new ErrorException ($errstr, 0, $errno, $errfile , $errline );
}
set_error_handler ("exception_error_handler" );
Problems with exceptions
● Some use them to control the flow of
  application
● Sometimes it's hard to distinguish which
  exception class to use
● Topic is not as much highlighted as it should
  be :(
Benefits (when used properly)
● Software is much more predictable and user
  friendly when there are some problems with
  external system (WebService) etc.
● It's much easier to find out what failed
● It's much easier to find the bug
Main advantages over error flags
(booleans, integers etc.)
● Much less "if" statements which results in
  more maintainable code
● You can explain why software fails by
  sending descriptive message and stack
  trace
Ideal exception
● Tells you what happened, why it happened
  and (if possible) how to fix it.
● Is ideal log message
● Is not thrown ;) Handle error in place where
  it happened if you can.

Eg.

●     new RuntimeException("Could not contact web service [url = $webServiceUrl, httpCode = $httpCode] to log user
      in [user id = $userId].");

●     throw new Canaldigital_PaymentService_Exception('Could not store customer product ' . "[Customer.id =
      {$customer->id}; Product.id = {$product->id}].");

●     throw new Exception("Auth server error"); // NOT!
Layer/library exceptions
● Use spl exceptions as much as possible
● Use "marker interface" to group exceptions
  thrown by library etc.
  eg. like in Symfony2, Zend Framework 2
namespace MyApi;
interface Exception {};
class RuntimeException extends RuntimeException {};
// so you can handle specific module/layer exceptions
try {
...
} catch (MyApiRuntimeException $myApiRuntimeEx) {
...
} catch (MyApiException $myApiEx) {
..
} catch (RuntimeException $runtimeEx) {
...
}
Do NOT!
● empty try-catch

  If you don't know what to do with
  exception/error just let it go up!

  At the point when context let you decide
  what to do now you can handle it in the right
  way.
PHPDoc
@throws DbException on DB error
or even better
@throws MethodNotAllowedHttpException //
self describing
Testing exceptions
● @expectedException
  InvalidArgumentException
● @expectedExceptionMessage Right
  Message (@see assertContains)
● @expectedExceptionCode 20
● http://www.phpunit.de/manual/current/en/writing-tests-for-phpunit.
    html#writing-tests-for-phpunit.exceptions
Appendix A - Exceptions in PHP doc
class LogicException extends Exception
Exception that represents error in the program logic.
This kind of exceptions should directly leed to a fix in your code
- Exception that represents error in the program logic. This kind of exceptions should directly lead to a fix in your code.


class BadFunctionCallException extends LogicException
Exception thrown when a function call was illegal.
- Exception thrown if a callback refers to an undefined function or if some arguments are missing.


class BadMethodCallException extends BadFunctionCallException
Exception thrown when a method call was illegal
- Exception thrown if a callback refers to an undefined method or if some arguments are missing.


class DomainException extends LogicException
Exception that denotes a value not in the valid domain was used.
This kind of exception should be used to inform about domain erors in mathematical sense.
- Exception thrown if a value does not adhere to a defined valid data domain.


class InvalidArgumentException extends LogicException
Exception that denotes invalid arguments were passed.
- Exception thrown if an argument does not match with the expected value.
Appendix A - Exceptions in PHP doc
class LengthException extends LogicException
Exception thrown when a parameter exceeds the allowed length.
This can be used for strings length, array size, file size, number of elements read from an Iterator and so on.
- Exception thrown if a length is invalid.


class OutOfRangeException extends LogicException
Exception thrown when an illegal index was requested.
This represents errors that should be detected at compile time.
- Exception thrown when an illegal index was requested. This represents errors that should be detected at compile time.


class RuntimeException extends Exception
Exception thrown for errors that are only detectable at runtime.


class OutOfBoundsException extends RuntimeException
Exception thrown when an illegal index was requested.
This represents errors that cannot be detected at compile time.
- Exception thrown if a value is not a valid key. This represents errors that cannot be detected at compile time.


class OverflowException extends RuntimeException
Exception thrown to indicate arithmetic/buffer overflow.
- Exception thrown when adding an element to a full container.
Appendix A - Exceptions in PHP doc
class RangeException extends RuntimeException
Exception thrown to indicate range errors during program execution.
Normally this means there was an arithmetic error other than under/overflow. This is the runtime version of DomainException.
- Exception thrown to indicate range errors during program execution. Normally this means there was an arithmetic error other than under/overflow. This is the runtime version of
DomainException.


class UnderflowException extends RuntimeException
Exception thrown to indicate arithmetic/buffer underflow.
- Exception thrown when performing an invalid operation on an empty container, such as removing an element.


UnexpectedValueException extends RuntimeException
- Exception thrown if a value does not match with a set of values. Typically this happens when a function calls another function and expects the return value to be of a certain type
or value not including arithmetic or buffer related errors.
Thank you :)
Ad

Recommended

Handling error & exception in php
Handling error & exception in php
Pravasini Sahoo
 
PHP - Introduction to PHP Error Handling
PHP - Introduction to PHP Error Handling
Vibrant Technologies & Computers
 
Php Error Handling
Php Error Handling
mussawir20
 
Errors, Exceptions & Logging (PHP Hants Oct '13)
Errors, Exceptions & Logging (PHP Hants Oct '13)
James Titcumb
 
Introduction to php exception and error management
Introduction to php exception and error management
baabtra.com - No. 1 supplier of quality freshers
 
Elegant Ways of Handling PHP Errors and Exceptions
Elegant Ways of Handling PHP Errors and Exceptions
ZendCon
 
Error reporting in php
Error reporting in php
Mudasir Syed
 
Exceptions in PHP
Exceptions in PHP
JanTvrdik
 
Types of Error in PHP
Types of Error in PHP
Vineet Kumar Saini
 
PHP - Introduction to PHP - Mazenet Solution
PHP - Introduction to PHP - Mazenet Solution
Mazenetsolution
 
Surprise! It's PHP :) (unabridged)
Surprise! It's PHP :) (unabridged)
Sharon Levy
 
Php(report)
Php(report)
Yhannah
 
Perl exceptions lightning talk
Perl exceptions lightning talk
Peter Edwards
 
Bioinformatica 27-10-2011-p4-files
Bioinformatica 27-10-2011-p4-files
Prof. Wim Van Criekinge
 
Lesson 4 constant
Lesson 4 constant
MLG College of Learning, Inc
 
PHP Basics
PHP Basics
Bhaktaraz Bhatta
 
Introduction to PHP
Introduction to PHP
Jussi Pohjolainen
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
wahidullah mudaser
 
Exception handling in ASP .NET
Exception handling in ASP .NET
baabtra.com - No. 1 supplier of quality freshers
 
Basic of PHP
Basic of PHP
Nisa Soomro
 
Exception handling in asp.net
Exception handling in asp.net
Neelesh Shukla
 
The PHP Way Of TDD - Think First, Code Later
The PHP Way Of TDD - Think First, Code Later
Hiraq Citra M
 
Methods of debugging - Atomate.net
Methods of debugging - Atomate.net
Vitalie Chiperi
 
Exception handling
Exception handling
Iblesoft
 
Error and Exception Handling in PHP
Error and Exception Handling in PHP
Arafat Hossan
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception Handling
P3 InfoTech Solutions Pvt. Ltd.
 
Presentation1
Presentation1
Anul Chaudhary
 
Php using variables-operators
Php using variables-operators
Khem Puthea
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
Jalpesh Vasa
 
Effective PHP. Part 6
Effective PHP. Part 6
Vasily Kartashov
 

More Related Content

What's hot (20)

Types of Error in PHP
Types of Error in PHP
Vineet Kumar Saini
 
PHP - Introduction to PHP - Mazenet Solution
PHP - Introduction to PHP - Mazenet Solution
Mazenetsolution
 
Surprise! It's PHP :) (unabridged)
Surprise! It's PHP :) (unabridged)
Sharon Levy
 
Php(report)
Php(report)
Yhannah
 
Perl exceptions lightning talk
Perl exceptions lightning talk
Peter Edwards
 
Bioinformatica 27-10-2011-p4-files
Bioinformatica 27-10-2011-p4-files
Prof. Wim Van Criekinge
 
Lesson 4 constant
Lesson 4 constant
MLG College of Learning, Inc
 
PHP Basics
PHP Basics
Bhaktaraz Bhatta
 
Introduction to PHP
Introduction to PHP
Jussi Pohjolainen
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
wahidullah mudaser
 
Exception handling in ASP .NET
Exception handling in ASP .NET
baabtra.com - No. 1 supplier of quality freshers
 
Basic of PHP
Basic of PHP
Nisa Soomro
 
Exception handling in asp.net
Exception handling in asp.net
Neelesh Shukla
 
The PHP Way Of TDD - Think First, Code Later
The PHP Way Of TDD - Think First, Code Later
Hiraq Citra M
 
Methods of debugging - Atomate.net
Methods of debugging - Atomate.net
Vitalie Chiperi
 
Exception handling
Exception handling
Iblesoft
 
Error and Exception Handling in PHP
Error and Exception Handling in PHP
Arafat Hossan
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception Handling
P3 InfoTech Solutions Pvt. Ltd.
 
Presentation1
Presentation1
Anul Chaudhary
 
Php using variables-operators
Php using variables-operators
Khem Puthea
 

Similar to Php exceptions (20)

Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
Jalpesh Vasa
 
Effective PHP. Part 6
Effective PHP. Part 6
Vasily Kartashov
 
Exception
Exception
baabtra.com - No. 1 supplier of quality freshers
 
Code Fast, Die Young, Throw Structured Exceptions
Code Fast, Die Young, Throw Structured Exceptions
John Anderson
 
Error handling
Error handling
Meherul1234
 
Errors, Exceptions & Logging (PHPNW13 Uncon)
Errors, Exceptions & Logging (PHPNW13 Uncon)
James Titcumb
 
Module-4_WTA_PHP Class & Error Handling
Module-4_WTA_PHP Class & Error Handling
SIVAKUMAR V
 
Exception Handling_ Mastering the Art of Dealing with Errors and Exceptions.pdf
Exception Handling_ Mastering the Art of Dealing with Errors and Exceptions.pdf
RamirezCarl
 
object oriented programming in PHP & Functions
object oriented programming in PHP & Functions
BackiyalakshmiVenkat
 
Design byexceptions
Design byexceptions
Asif Tasleem
 
Code Fast, die() Early, Throw Structured Exceptions
Code Fast, die() Early, Throw Structured Exceptions
John Anderson
 
PHP Exception handler
PHP Exception handler
Ravi Raj
 
errors in php 7
errors in php 7
Damien Seguy
 
Exception handling
Exception handling
zindadili
 
Lecture 3.1.1 Try Throw Catch.pptx
Lecture 3.1.1 Try Throw Catch.pptx
sunilsoni446112
 
9781337102087 ppt ch14
9781337102087 ppt ch14
Terry Yoast
 
TDC 2015 - POA - Trilha PHP - Shit Happens
TDC 2015 - POA - Trilha PHP - Shit Happens
Jackson F. de A. Mafra
 
Exception handling chapter15
Exception handling chapter15
Kumar
 
Review unknown code with static analysis - bredaphp
Review unknown code with static analysis - bredaphp
Damien Seguy
 
Exception Handling
Exception Handling
baabtra.com - No. 1 supplier of quality freshers
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
Jalpesh Vasa
 
Code Fast, Die Young, Throw Structured Exceptions
Code Fast, Die Young, Throw Structured Exceptions
John Anderson
 
Errors, Exceptions & Logging (PHPNW13 Uncon)
Errors, Exceptions & Logging (PHPNW13 Uncon)
James Titcumb
 
Module-4_WTA_PHP Class & Error Handling
Module-4_WTA_PHP Class & Error Handling
SIVAKUMAR V
 
Exception Handling_ Mastering the Art of Dealing with Errors and Exceptions.pdf
Exception Handling_ Mastering the Art of Dealing with Errors and Exceptions.pdf
RamirezCarl
 
object oriented programming in PHP & Functions
object oriented programming in PHP & Functions
BackiyalakshmiVenkat
 
Design byexceptions
Design byexceptions
Asif Tasleem
 
Code Fast, die() Early, Throw Structured Exceptions
Code Fast, die() Early, Throw Structured Exceptions
John Anderson
 
PHP Exception handler
PHP Exception handler
Ravi Raj
 
Exception handling
Exception handling
zindadili
 
Lecture 3.1.1 Try Throw Catch.pptx
Lecture 3.1.1 Try Throw Catch.pptx
sunilsoni446112
 
9781337102087 ppt ch14
9781337102087 ppt ch14
Terry Yoast
 
TDC 2015 - POA - Trilha PHP - Shit Happens
TDC 2015 - POA - Trilha PHP - Shit Happens
Jackson F. de A. Mafra
 
Exception handling chapter15
Exception handling chapter15
Kumar
 
Review unknown code with static analysis - bredaphp
Review unknown code with static analysis - bredaphp
Damien Seguy
 
Ad

Recently uploaded (20)

Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
PyCon SG 25 - Firecracker Made Easy with Python.pdf
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
"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
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
janeliewang985
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
PyCon SG 25 - Firecracker Made Easy with Python.pdf
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
"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
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
janeliewang985
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
Ad

Php exceptions

  • 1. PHP Exceptions tips How to use exceptions properly? Damian Sromek damiansromek.pl 2012-05
  • 2. What's an exception? Software can not finish task by performing regular scenario and you should not ignore it. ● External system does not work eg. database, network, filesystem ● Software is used/configured wrong eg. credentials not set ● There's a bug in software eg. somehow program came to invalid state, object was requested to do something inappropriate / "stupid"
  • 3. What's NOT an exception? Software can not finish a task but you know it's nothing strange when some criteria are not met. ● Validator failure eg. wrong form field value, wrong credentials when logging in Database access methods ● findByPK - should return "null" if no unique result ● findAll - should return empty collection if no results
  • 4. Main types of exceptions ● LogicException Software got to wrong state but it will not happen again when programmer fixes the code eg. filling missing configuration, better form validation ● RuntimeException Software got to wrong state because of external dependency that could not have been avoided any way eg. network error, database failure
  • 5. PHP spl exceptions http://php.net/manual/en/language.exceptions.php http://www.php.net/manual/en/spl.exceptions.php Sadly there's not much about exceptions in PHP documentation. http://www.php.net/~helly/php/ext/spl/classException.html Exception LogicException BadFunctionCallException BadMethodCallException DomainException InvalidArgumentException LengthException OutOfRangeException RuntimeException OutOfBoundsException OverflowException RangeException UnderflowException UnexpectedValueException
  • 6. Exceptions instead of PHP errors Convert PHP errors to exception to get better control over your software http://www.php.net/manual/en/class.errorexception.php <?php function exception_error_handler ($errno, $errstr, $errfile , $errline ) { throw new ErrorException ($errstr, 0, $errno, $errfile , $errline ); } set_error_handler ("exception_error_handler" );
  • 7. Problems with exceptions ● Some use them to control the flow of application ● Sometimes it's hard to distinguish which exception class to use ● Topic is not as much highlighted as it should be :(
  • 8. Benefits (when used properly) ● Software is much more predictable and user friendly when there are some problems with external system (WebService) etc. ● It's much easier to find out what failed ● It's much easier to find the bug
  • 9. Main advantages over error flags (booleans, integers etc.) ● Much less "if" statements which results in more maintainable code ● You can explain why software fails by sending descriptive message and stack trace
  • 10. Ideal exception ● Tells you what happened, why it happened and (if possible) how to fix it. ● Is ideal log message ● Is not thrown ;) Handle error in place where it happened if you can. Eg. ● new RuntimeException("Could not contact web service [url = $webServiceUrl, httpCode = $httpCode] to log user in [user id = $userId]."); ● throw new Canaldigital_PaymentService_Exception('Could not store customer product ' . "[Customer.id = {$customer->id}; Product.id = {$product->id}]."); ● throw new Exception("Auth server error"); // NOT!
  • 11. Layer/library exceptions ● Use spl exceptions as much as possible ● Use "marker interface" to group exceptions thrown by library etc. eg. like in Symfony2, Zend Framework 2 namespace MyApi; interface Exception {}; class RuntimeException extends RuntimeException {}; // so you can handle specific module/layer exceptions try { ... } catch (MyApiRuntimeException $myApiRuntimeEx) { ... } catch (MyApiException $myApiEx) { .. } catch (RuntimeException $runtimeEx) { ... }
  • 12. Do NOT! ● empty try-catch If you don't know what to do with exception/error just let it go up! At the point when context let you decide what to do now you can handle it in the right way.
  • 13. PHPDoc @throws DbException on DB error or even better @throws MethodNotAllowedHttpException // self describing
  • 14. Testing exceptions ● @expectedException InvalidArgumentException ● @expectedExceptionMessage Right Message (@see assertContains) ● @expectedExceptionCode 20 ● http://www.phpunit.de/manual/current/en/writing-tests-for-phpunit. html#writing-tests-for-phpunit.exceptions
  • 15. Appendix A - Exceptions in PHP doc class LogicException extends Exception Exception that represents error in the program logic. This kind of exceptions should directly leed to a fix in your code - Exception that represents error in the program logic. This kind of exceptions should directly lead to a fix in your code. class BadFunctionCallException extends LogicException Exception thrown when a function call was illegal. - Exception thrown if a callback refers to an undefined function or if some arguments are missing. class BadMethodCallException extends BadFunctionCallException Exception thrown when a method call was illegal - Exception thrown if a callback refers to an undefined method or if some arguments are missing. class DomainException extends LogicException Exception that denotes a value not in the valid domain was used. This kind of exception should be used to inform about domain erors in mathematical sense. - Exception thrown if a value does not adhere to a defined valid data domain. class InvalidArgumentException extends LogicException Exception that denotes invalid arguments were passed. - Exception thrown if an argument does not match with the expected value.
  • 16. Appendix A - Exceptions in PHP doc class LengthException extends LogicException Exception thrown when a parameter exceeds the allowed length. This can be used for strings length, array size, file size, number of elements read from an Iterator and so on. - Exception thrown if a length is invalid. class OutOfRangeException extends LogicException Exception thrown when an illegal index was requested. This represents errors that should be detected at compile time. - Exception thrown when an illegal index was requested. This represents errors that should be detected at compile time. class RuntimeException extends Exception Exception thrown for errors that are only detectable at runtime. class OutOfBoundsException extends RuntimeException Exception thrown when an illegal index was requested. This represents errors that cannot be detected at compile time. - Exception thrown if a value is not a valid key. This represents errors that cannot be detected at compile time. class OverflowException extends RuntimeException Exception thrown to indicate arithmetic/buffer overflow. - Exception thrown when adding an element to a full container.
  • 17. Appendix A - Exceptions in PHP doc class RangeException extends RuntimeException Exception thrown to indicate range errors during program execution. Normally this means there was an arithmetic error other than under/overflow. This is the runtime version of DomainException. - Exception thrown to indicate range errors during program execution. Normally this means there was an arithmetic error other than under/overflow. This is the runtime version of DomainException. class UnderflowException extends RuntimeException Exception thrown to indicate arithmetic/buffer underflow. - Exception thrown when performing an invalid operation on an empty container, such as removing an element. UnexpectedValueException extends RuntimeException - Exception thrown if a value does not match with a set of values. Typically this happens when a function calls another function and expects the return value to be of a certain type or value not including arithmetic or buffer related errors.