Php Exception Handling and php exception capture
The try {thow} catch () {} Exception Handling structure can effectively control multiple lines of code that may cause exceptions. The basic model is as follows:
<? Phptry {throw new Exception ("error message";) // throw an error} catch (Exception $ e) // capture error information, exception is a built-in error handling class {echo $ e-> getMessage (); // output the error message echo $ e-> getCode (); // return the Exception Code echo $ e-> getFile (); // return the abnormal file echo $ e-> getLine (); // return the abnormal row number}?>
Exception:
<? Phpclass Exception {protected $ message = 'unknown exception'; // exception information private $ string; // _ toString cache protected $ code = 0; // User-Defined Exception Code protected $ file; // the file name protected $ line when an exception occurs; // The code line with the exception is private $ trace; // backtrace private $ previous; // previous exception if nested exception public function _ construct ($ message = null, $ code = 0, Exception $ previous = null); final private function _ c Lone (); // Inhibits cloning of exceptions. final public function getMessage (); // returns the exception message final public function getCode (); // returns the Exception Code final public function getFile (); // return the file name final public function getLine () for which an exception occurs; // return the code line number final public function getTrace (); // backtrace () array final public function getPrevious (); // The previous exception final public function getTraceAsString (); // getTrace () Message formatted as a string Public function _ toString (); // output string}?>
At the same time, a try can also be associated with multiple catch blocks. You can customize the class to inherit the Exception class.
<? Php class myException1 extends Exception {} // customize class myException2 extends Exception {} class myException3 extends Exception {} try {switch (1) {case 1: throw new myException1 (); case 2: throw new myException2 (); case 3: throw new myException3 (); // when the catch code block cannot be found, will be thrown to Exception Processing, because myException3 inherits Exception} catch (myException1 $ e) {echo "custom error 1";} catch (myException2 $ e) {echo "custom error 2";} catch (E Xception $ e) {echo "original exception class" ;}?>