/**
PHP异常处理
javaVSphp 之异常(简单记一笔)
java 函数外:抛的throws
函数内:抛的throw
php只有 函数内:抛的throw;
什么时候try{}cath(){} //什么时候捕获
1.就是你能处理的你就捕获
2.不能处理的就只有抛了
比喻:打个比喻不是很形象哈
比如你开发一个图片处理模块
你的图片处理库只有2个
1.jpg图片处理库
2.png图片处理库
//写下面这段代码的时候你就会想,我这里只有个2个图片处理库,没有第3个了,
如果用户给我传一个 GIF的图片
怎么办呢?
我这程序是处理不了的,
这就叫我不能处理的问题了,那就直接抛出就行了
switch (检查图片类型..){
case ' jpg' :
调用我的 jpg图片处理库
case 'png':
调用我的png图片处理库
default :
你这里就可以直接抛出了
throw new Exception ('-_-我只能对jp/pn进行处理');
}
function compile($filename) {
$content = file_get_contents($filename);
// 替换预编译指令
$content = preg_replace('/\/\/\[RUNTIME\](.*?)\/\/\[\/RUNTIME\]/s', '', $content);
$content = substr(trim($content), 5);
if ('?>' == substr($content, -2))
$content = substr($content, 0, -2);
return $content;
}
****/
class NumberIndexException extends Exception {
Public function __Construct($msg) {
parent :: __Construct($msg);
}
Public function __toString(){
return $this->message .'--'.$this->code.'--'.$this->file.'--'.$this->line;
}
}
class Demo {
Public static function method(array $arr, $index) {
if ($index<0)
throw new NumberIndexException ("-_-不能处理了负数下标的出现了...");
return $arr[$index];
}
}
class ExceptionsDemo {
/**自定义主函数*/
Public Static function Main(){
$arr = array (1,2,3);
try{
$sum = Demo::method($arr,-30);
echo 'sum='.$sum; //输出
} catch(NumberIndexException $e) {
echo '异常...';
echo '<pre>';
echo 'message:'.$e->getMessage(); //取得信息
echo $e->getCode();
echo $e->getFile();
echo $e->getLine();
echo '<hr/>';
echo $e->getTrace();
echo $e->getTraceAsString();//打印出在堆栈中的信息
echo '<hr/>';
echo $e->__toString(); //把对象转换为字符串
echo '</pre>';
}
}
}
header("Content-Type:text/html;charset=utf-8;");
ExceptionsDemo :: Main(); //入口
转载于:https://my.oschina.net/u/1246814/blog/265043