PHP基础知识系列:错误处理与异常处理

一、基本错误处理:die(),发生错误之后终止了脚本运行。

if(!file_exists("welecome.txt")){   
  die("File not fount");//自定义显示的错误信息 
}else{   
  $file = fopen("welecome.txt","r"); 
} 

简单地直接终止了脚本并不总是恰当的。

面向对象的错误处理方法:异常处理,用于在指定的错误发生时改变脚本的正常流程。

function checkNum($number){
  if($number > 1){
    throw new Exception("value must be 1 or below");
  }
  return true;
}

//在try代码块中触发异常
try{
  checkNum(2);
  echo "success";
}catch(Exception $e){
  echo 'Message:'.$e->getMessage();
}
原文地址:https://www.cnblogs.com/colorstory/p/2658592.html