Error Handling and Exception

时间:2021-09-28 21:33:56

The default error handling in PHP is very simple.An error message with filename, line number and a message describing the error is sent to the browser.

PHP has different error handling methods:

  • Simple "die()" statements
  • Custom errors and error triggers
  • Error reporting

Using the die() function

<?php

  if(!file_exists(""a.txt)){  

    die("File not found");

  }else{

    $file = fopen("a.txt", "r");

  }

?>

Creating a Custom Error Handler

Creating a custom error handler is quite simple.We simply create a special function that can be called when an error occurs in PHP.

The function must be able to handle a minimun of 2 parameters(error level and message) but can accept up to 5 parameters(optionally: file, line-number, and the error context)

error_function(error_level, error_message, error_file, error_line, error_context);

error_level: required.Specifies the error report level for the user-defined error.Must be a value number.

error_message: required.Specifies the error message for the user-defined error.

error_file: optional.Specifies the filename in which the error occurred.

error_line: optional.Specifies the line number in which the error occurred.

error_context: optional.Specifies an array containing every variable, and their values, in use the error occurred

error_levels:

2  E_WARNING  Nonn-fatal run-time errors.Execution of the script is not halted

8  E_NOTICE  Run-time notices.The script found something that might be an error, but could also happen when running a script normally

256  E_USER_ERROR  Fatal user-generated error.This is like an E_ERROR set by the programmer using the PHP function trigger_error()

512  E_USER_WARNING  Non-fatal user-generated warning.This is like an E_WARNING set by the programmer using the PHP function trigger_error()

1024  E_USER_NOTICE  User-generated notice.This is like an E_NOTICE set by the programmer using the PHP function trigger_error()

4096  E_RECOVERABLE_ERROR  Catchable fatal error.This is like an E_ERROR but can be caught by a user define handle

8191  E_ALL  All the errors and warnings

<?php

  function customError($errno, $errstr){

    echo "<b>Error:</b>[$errno] $errstr<br>";

    echo "Ending script";

    die();

  }

?>

The default error handler for PHP is the built in error handler.We are going to make the function above the default error handler for the duration of the script.

set_error_handler("customError");

<?php

  function customError($errno, $errStr){

    echo "<b>Error:</b>[$errno] $errstr<br>";

  }

  

  set_error_handler("cutomError");

  

  echo($test); //Error: [8] Undefined variable: test

?>

In a script where users can input data it is useful to trigger errors when an illegal input occurs.In PHP, this is done by the trigger_error() function.

<?php

  $test = 2;

  if($test > 1){

    trigger_error("Value must be 1 or below");// Notice: Value must be 1 or below

  }

?>

An error type can be triggered anywhere you wish in a script, and by adding a second parameter, you can specify what error level is triggered.

Possible error types:

  • E_USER_ERROR    Fatal user-generated run-time error.Errors that can not be recovered from.Execution of the script is halted
  • E_USER_WARNING    Non-fatal user-generated run-time warning.Execution of the script is not halted
  • E_USER_NOTICE    Default.User-generated run-time notice.The script found something that might be an error, but could also happen when running a script normally

Error Logging

By default, PHP sends an error log to the server's logging system or a file, depending on how the error_log configuration is set in the php.ini file.By using the error_log() function you can send error logs to a specified or a remote destination.

<?php

  //error handler function

  function customError($errno, $errstr){

    echo "<b>Error:</b> [$errno] $errstr</br>";

    echo "Webmaster has been notified";

    error_log("Error: [$errno] $errstr", 1, "xx@xxx.com", "From: webmaster@xx.com");

  }

  set_error_handler("customError", E_USER_WARNING);

  $test = 2;

  if($test > 1){

    trigger_error("Value must be 1 or below", E_USER_WARNING);

  }

?>

Exceptions are used to change the normal flow of a script if a specified error occurs.

PHP has different error handling methods:

  • Basic use of Exception
  • Creating a custom exception handler
  • Multiple exceptions
  • Re-throwing an exception
  • Setting a top level exception handler

Basic Use of Exceptions

<?php

  function checkNum($number){

    if($number > 1){

      throw new Exception("Value must be 1 or below");

    }

    return true;

  }

  

  checkNum(2);

?>

Try, throw and catch

Proper exception code shoule include:

Try--A fucntion using an exception should be in a "try" block.If the exception does not trigger, the code will continue as normal.However if the exception triggers, an exception is "thrown"

Throw--This is how you trigger an exception.Each "throw" must have at least one "catch"

Catch--A "catch" block retrieves an exception and creates an object containing the exception information

<?php

  function checkNum($number){

    if($number > 1){

      throw new Exception("Value must be 1 or below");

    }

    return true;

  }

  try{

    checkNum(2);

    echo 'If you see this, the number is 1 or below';

  }

  catch(Exception $e){

    echo 'Message: '  .$e->getMessage();

  }

?>

Creating a Custom Exception Class

To create a custom exception handler you must create a special class with functions that can be called when an exception occurs in PHP.The class must be an extension of the exception class.

The custom exception class inherits the properties from PHP's exception class and you can ad customm functions to it.

<?php

  class customException extends Exception{

    public function errorMessage(){

      $errorMsg = 'Error on line ' .$this->getLine().'  in ' .$this->getFile(). ':<b>' .$this->getMessage(). '</b> is not a valid E-Mail address' ;

      return $errorMsg;

    }

  }

  $email = "xx@xx.....com";

  try{

    if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){

      throw new customException($email);

    }

  }

  catch(customException $e){

    echo $e->errorMessage();

  }

?>

<?php

  class customException extends Exception{

    public function errorMessage(){

      $errorMsg = 'Error on line ' .$this->getLine(). ' in ' .$this->getFile() . ': <b>' .$this->getMessage().'</b> is not  a valid Email address'.

      return $errorMsg;

    }

  }

  $email = "xxx@xx.com";

  try{

    if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){  

      throw new customException($email);

    }

    if(strpos($email, "example") !== false){

      throw new Exception("$email is an example e-mail");

    }

  }

  catch(customException $e){  

    echo $e -> errorMessage();

  }

  catch(Exception $e){

    echo $e ->getMessage();

  }

?>

<?php

  class customException extends Exception{

    public function errorMessage{

      $errorMsg =$this->getMessage().' is not a valid E-Mail address';

      return $errorMsg;

    }

  }

  

  $email = "xx@xx.com";

  

  try{

    try{

      if(strpos($email, "example") !== false)

        throw new Exception($email);

      }

    }

    catch(Exception $e){

      throw new customException($email);

    }

  }

  catche(customException $e){

    echo $e->errorMessage();

  }

?>

<?php

  function myException($exception){

    echo "<b>Exception:</b>" .$exception->getMessage();
  }

  set_exception_handler('myException');

  throw new Exception('Uncaught Exception occured');

?>

Rules for exceptions

  • Code may be surrounded in a try block, to help catch potential exceptions
  • Each try block or "throw" must have at least one corresponding catch block
  • Multiple catch blocks can be used to catch different classed of exceptions
  • Exceptions can be thrown in a catch block within a try block

Error Handling and Exception的更多相关文章

  1. TIJ——Chapter Twelve&colon;Error Handling with Exception

    Exception guidelines Use exceptions to: Handle problems at the appropriate level.(Avoid catching exc ...

  2. setjmp&lpar;&rpar;、longjmp&lpar;&rpar; Linux Exception Handling&sol;Error Handling、no-local goto

    目录 . 应用场景 . Use Case Code Analysis . 和setjmp.longjmp有关的glibc and eglibc 2.5, 2.7, 2.13 - Buffer Over ...

  3. Error Handling

    Use Exceptions Rather Than Return Codes Back in the distant past there were many languages that didn ...

  4. Clean Code&ndash&semi;Chapter 7 Error Handling

    Error handling is important, but if it obscures logic, it's wrong. Use Exceptions Rather Than Return ...

  5. beam 的异常处理 Error Handling Elements in Apache Beam Pipelines

    Error Handling Elements in Apache Beam Pipelines Vallery LanceyFollow Mar 15 I have noticed a defici ...

  6. Fortify漏洞之Portability Flaw&colon; File Separator 和 Poor Error Handling&colon; Return Inside Finally

    继续对Fortify的漏洞进行总结,本篇主要针对 Portability Flaw: File Separator 和  Poor Error Handling: Return Inside Fina ...

  7. Error handling in Swift does not involve stack unwinding&period; What does it mean&quest;

    Stack unwinding is just the process of navigating up the stack looking for the handler. Wikipedia su ...

  8. WCF Error Handling

    https://docs.microsoft.com/en-us/dotnet/framework/wcf/wcf-error-handling The errors encountered by a ...

  9. ASP&period;NET Error Handling

    https://docs.microsoft.com/en-us/aspnet/web-forms/overview/getting-started/getting-started-with-aspn ...

随机推荐

  1. java 20 - 8 字节流的文件复制以及汉字在计算机中的存储方式

    复制文本文件:把当前目录下的FileIntputStream.java文件里面的内容复制到当前目录的b.txt文件中 分析: 数据源: FileIntputStream.java -- 读取数据 -- ...

  2. &lbrack;转&rsqb;GameObject的Active与InActive

    GameObject的Active与InActive 1.Script可以控制InActive的GameObject,但前提是Script所依附的GameObject不能是InActive,一旦为In ...

  3. 利用 Ant 和 Eclipse 有效地提高部署工作效率

    读者定位为具有 Java 和 Ant 使用经验的开发人员. 读者可以学习到如何使用 Ant 解决一些多用户开发环境中,根据不同的目标环境编译成不同部署包的问题. 工作场景 现在有一个 web 项目,是 ...

  4. log4j日志输出到web项目指定文件夹

    感谢 eric2500 的这篇文章:http://www.cxyclub.cn/n/27860/ 摘要:尝试将log4j的文件日志输出到web工程制定目录,遇到了很多问题,最终在eric2500的指导 ...

  5. 在不连接网线的情况下Windos与VM之间如何ping通

    一般情况下,如果宿主主机的网口连接网线并且能够上网,那么按照VM的默认安装,在VM-Settings-Hardware-Network Adapter-Network connection中选择Bri ...

  6. 无刷新更新listview

    闲来无事,写点水文吧!有用得着的可以参考下,无刷新更新listview是什么意思呢?举个例子,在订单类listview列表中,常常会有各种订单状态,拿商城类app来说,会有待付款,待收货,确认收货等等 ...

  7. 2018牛客网暑期ACM多校训练营(第三场)C Shuffle Cards(可持久化平衡树&sol;splay)

    题意 牌面初始是1到n,进行m次洗牌,每次抽取一段放到最前面.求最后的序列. 分析 神操作!!!比赛时很绝望,splay技能尚未点亮,不知道怎么用. 殊不知,C++库里有rope神器,即块状链表. 基 ...

  8. beego 初体验 - 环境搭建

    首先,安装go运行时和beego beego,在git bash 运行命令: go get github.com/beego/bee go get github.com/astaxie/beego g ...

  9. AnswerOpenCV一周佳作欣赏&lpar;0615-0622&rpar;

    一.How to make auto-adjustments(brightness and contrast) for image Android Opencv Image Correction i' ...

  10. Parking Lot CodeForces - 480E

    大意: 给定01矩阵, 单点赋值为1, 求最大全0正方形. 将询问倒序处理, 那么答案一定是递增的, 最多增长$O(n)$次, 对于每次操作暴力判断答案是否增长即可, 也就是说转化为判断是否存在一个边 ...