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 can you create and handle custom exception classes in PHP? | ComputerScienceOne | Bifalgorithm | Bifalgorithm