Error Handling and Exception

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, "[email protected]", "From: [email protected]");

  }

  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 = "[email protected]";

  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 = "[email protected]";

  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 = "[email protected]";

  

  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
时间: 2024-11-06 08:12:24

Error Handling and Exception的相关文章

setjmp()、longjmp() Linux Exception Handling/Error Handling、no-local goto

目录 1. 应用场景 2. Use Case Code Analysis 3. 和setjmp.longjmp有关的glibc and eglibc 2.5, 2.7, 2.13 - Buffer Overflow Vulnerability 1. 应用场景 非局部跳转通常被用于实现将程序控制流转移到错误处理模块中:或者是通过这种非正常的函数返回机制,返回到之前调用的函数中 1. setjmp.longjmp的典型用途是异常处理机制的实现:利用longjmp恢复程序或线程的状态,甚至可以跳过栈中

Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十二)之Error Handling with Exceptions

The ideal time to catch an error is at compile time, before you even try to run the program. However, not all errors can be detected at compile time. To create a robust system, each component must be robust. By providing a consistent error-reporting

转 InnoDB Error Handling

14.20.4 InnoDB Error Handling Error handling in InnoDB is not always the same as specified in the SQL standard. According to the standard, any error during an SQL statement should cause rollback of that statement. InnoDB sometimes rolls back only par

[RxJS] Error handling operator: catch

Most of the common RxJS operators are about transformation, combination or filtering, but this lesson is about a new category, error handling operators, and its most important operator: catch(). Basic catch( err => Observable): var foo = Rx.Observabl

java virtual machine launcher Error:Could not create the Java Virtual Machine. Error:A Fatal exception has occurred,Program will exit.

Error:Could not create the Java Virtual Machine. Error:A Fatal exception has occurred,Program will exit. 出现以上错误信息提示,如下图所示: 然后点击确定弹出以下错误信息 解决办法: 1.判断机子是否安装了Java环境.具体方法网上搜吧,这里还是给小白一个传送门:(设置) 注意设置自己的环境变量:如JAVA_HOME,CLASSPATH,PATH 2.有些程序会有内存设置,有些程序内存设置过大

keytool error: java.lang.Exception: Certificate not imported, alias already exists

Error Command to import the certificate into the Java keystore fails with the following error: keytool error: java.lang.Exception: Certificate not imported, alias already exists Cause Alias already exist. Needs to removed previous alias before adding

MySQL Error Handling in Stored Procedures 2

Summary: this tutorial shows you how to use MySQL handler to handle exceptions or errors encountered in stored procedures. When an error occurs inside a stored procedure, it is important to handle it appropriately, such as continuing or exiting the c

MySQL Error Handling in Stored Procedures---转载

This tutorial shows you how to use MySQL handler to handle exceptions or errors encountered in stored procedures. When an error occurs inside a stored procedure, it is important to handle it appropriately, such as continuing or exiting the current co

Kafka中错误:Unrecognized VM option ‘UseCompressedOops’ Error: Clould not create the Java Vritual Machine. Error: A fatal exception has occurres . Program will exit.

错误的描述: 在kafka安装目录下,执行 $ bin/zookeeper-server-start.sh config/zookeeper.properties & Unrecognized VM option ‘UseCompressedOops’ Error: Clould not create the Java Vritual Machine. Error: A fatal exception has occurres . Program will exit. 解决方法: 找到bin/k