Concept
How can you create and handle custom exception classes in PHP?
ComputerScienceOne / Creating Custom Exceptions
"As of PHP 5.3.0 it is possible to define custom exceptions by extending the Exception class. To do this, you need to declare a new class. We cover classes and objects in Chapter 45. For now, we present a simple example. Consider the example in the previous chapter of computing the roots of a quadratic polynomial. One possible error situation is when the roots are complex numbers. We could define a new PHP exception class as follows.\n\n/**\n\n* Defines a ComplexRoot exception class\n\n*/\n\nclass ComplexRootException extends Exception\n\n{\n\npublic function __construct($message = null,\n\n$code = 0,\n\nException $previous = null) {\n\n// call the parent constructor\n\nparent::__construct($message, $code, $previous);\n\n}\n\n// custom string representation of object\n\npublic function __toString() {\n\nreturn __CLASS__ . \": [{$this->code}]: {$this->message}\n\n\";\n\n}\n\n}\n\nNow in our code we can catch and even throw this new type of exception.\n\nif( $b*$b - 4*$a*$c < 0) {\n\nthrow new ComplexRootException(\"Cannot Handle complex roots\");\n\n}\n\ntry {\n\n$r1 = getRoot($a, $b, $c);\n\n} catch(ComplexRootException $e) {\n\n//handle here\n\n} catch(Exception $e) {\n\n//handle all other types of exceptions here\n\n}\n\nIn the code above we had two catch blocks. Since we can have multiple types of exceptions, we can catch each different type and handle them differently if we choose. Each catch block catches a different type of exception. The last catch block was written to catch a generic Exception. Much like an if-else-if statement, the first type of exception that is caught is the block that will be executed and they are all mutually exclusive. Thus, a generic “catch all” block like this should always be the last catch block. The most specific types of exceptions should be caught first and the most general types should be caught last."
Related Ideas
- How does PHP support throwing and defining exceptions?ComputerScienceOne · Throwing Exceptions
- Why should the most specific exception types be caught before the most general types?ComputerScienceOne · Creating Custom Exceptions
- How do you catch exceptions in PHP?ComputerScienceOne · Catching Exceptions
- How do you throw exceptions in PHP?ComputerScienceOne · Catching Exceptions
- How do you create a custom exception in Java?ComputerScienceOne · Creating Custom Exceptions
- How can Java handle different exception types with multiple catch blocks?ComputerScienceOne · Catching Exceptions
- How can conditionals handle invalid and special cases in a quadratic roots program?ComputerScienceOne · Quadratic Roots Revisited
- Why must software handle errors in addition to avoiding bugs?ComputerScienceOne · Error Handling