Preview:
DESCRIPTION
Best practices for using exceptions in PHP. How to design exception hierarchies. Difference between runtime and usage (logic) error.
Citation preview
- Jan Tvrdk
- try { ... if (!$ok) { throw new FooException(); }} catch
(FooException $e) { ...}
- try { ... if (!$ok) { throw new FooException(); }} catch
(FooException $e) { ...} catch (BarException $e) { ...}
- try { ... if (!$ok) { throw new FooException(); }} catch
(FooException $e) { ...} finally { ...}
- try No Was there an exception thrown?Yes Is there a
corresponding No catch block?Yes catch finally
- try { $this->db->lock(users);
$this->db->query(...); $this->db->unlock();//
intentionally catch all exceptions} catch (Exception $e) {
$this->db->unlock(); throw $e;}
- try { $this->db->lock(users);
$this->db->query(...); $this->db->unlock();//
intentionally catch all exceptions} catch (Exception $e) {
$this->db->unlock(); throw $e;}
- try { $this->db->lock(users);
$this->db->query(...);} finally {
$this->db->unlock();}
- try { return 1;} finally { return 2;}
- constructor parameters string $message = "" int $code = 0
Exception $previous = NULLmethods string getMessage() Exception
getPrevious() mixed getCode() string getFile() int getLine() array
getTrace()
- usage errorruntime error System failure
- can be avoidedshould directly lead to a fixmessage is more
important than typevery important in librariesshould not be
catchedexamples: wrong argument type / value calling method in
incorrect order creating an instance of static class calling not
implemented method
- can NOT be avoidedtype is more important than messageshould be
catchedoften related to thread safetyexamples: file / directory /
database entry not found duplicate entry in database
- ExceptionErrorExceptionLogicException (for usage errors)
InvalidArgumentExceptionRuntimeException (for runtime errors)
- Exception LogicException AppLogicException
AppInvalidArgumentException AppNotImplementedException
AppStaticClassException RuntimeException
- Exception LogicException RuntimeException AppRuntimeException
AppIOException AppFileNotFoundException
AppDirectoryNotFoundException AppEntryNotFoundException
AppDuplicateEntryException
- throw only exceptions from your namespaceusage error write nice
ex. message for human developerruntime error use very specific type
(often requires creating a new one) message is often uselessphpDoc
Always specify all runtime exceptions @throw annotation is part of
API
- never display ex. message to the usercatch as specific types as
possibleread and respect @throw annotationsuse $previous when
rethrowing ex.
- Twitter + GitHub @JanTvrdik nette.merxes.cz