- 基本格式:
try{
/* code block*/
} catch(Exception $e){ # $e是异常类的实例对象
/* handle code */
} finally{
/* finally code */
}
- 手动引发异常:
throw new Exception($message, $code);
- Exception Class method:
getCode() // Returns the code as passed to the constructor
getMessage() // Returns the message as passed to the constructor
getFile() //Returns the full path to the code file where the exception was raised
getLine() //Returns the line number in the code file where the exception was raised
getTrace() //Returns an array containing a backtrace where the exception was raised
getTraceAsString() //Returns the same information as getTrace, formatted as a string
getPrevious() //Returns the previous exception (from the third parameter to the constructor)
__toString() //Allows you to simply echo an Exception object, giving all the information from the above methods, 即直接以字符串的形式显示$e,等同于echo $e
-
用户自定义的异常:
Exception基类中除了__toString()是公有方法外,其它方法均为final,所以用户只能修改__toString()方法来更改显示样式及异常类的名称。 # 通过不同的异常类可以方便地排查错误 -
用错误抑制符@修饰的代码在发生错误时无论是否引发异常(取决于php.ini的配置)都会产生警告。