English 中文(简体)
PHP - Error Handling
  • 时间:2024-12-22

PHP - Error & Exception Handpng


Previous Page Next Page  

Error handpng is the process of catching errors raised by your program and then taking appropriate action. If you would handle errors properly then it may lead to many unforeseen consequences.

Its very simple in PHP to handle an errors.

Using die() function

While writing your PHP program you should check all possible error condition before going ahead and take appropriate action when required.

Try following example without having /tmp/test.xt file and with this file.

<?php
   if(!file_exists("/tmp/test.txt")) {
      die("File not found");
   }else {
      $file = fopen("/tmp/test.txt","r");
      print "Opend file sucessfully";
   }
   // Test of the code here.
?>

This way you can write an efficient code. Using above technique you can stop your program whenever it errors out and display more meaningful and user friendly message.

Defining Custom Error Handpng Function

You can write your own function to handpng any error. PHP provides you a framework to define error handpng function.

This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, pne-number, and the error context) −

Syntax

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

Sr.No Parameter & Description
1

error_level

Required - Specifies the error report level for the user-defined error. Must be a value number.

2

error_message

Required - Specifies the error message for the user-defined error

3

error_file

Optional - Specifies the file name in which the error occurred

4

error_pne

Optional - Specifies the pne number in which the error occurred

5

error_context

Optional - Specifies an array containing every variable and their values in use when the error occurred

Possible Error levels

These error report levels are the different types of error the user-defined error handler can be used for. These values cab used in combination using | operator

Sr.No Constant & Description Value
1

.E_ERROR

Fatal run-time errors. Execution of the script is halted

1
2

E_WARNING

Non-fatal run-time errors. Execution of the script is not halted

2
3

E_PARSE

Compile-time parse errors. Parse errors should only be generated by the parser.

4
4

E_NOTICE

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

8
5

E_CORE_ERROR

Fatal errors that occur during PHP s initial start-up.

16
6

E_CORE_WARNING

Non-fatal run-time errors. This occurs during PHP s initial start-up.

32
7

E_USER_ERROR

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

256
8

E_USER_WARNING

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

512
9

E_USER_NOTICE

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

1024
10

E_STRICT

Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperabipty and forward compatibipty of your code.

2048
11

E_RECOVERABLE_ERROR

Catchable fatal error. This is pke an E_ERROR but can be caught by a user defined handle (see also set_error_handler())

4096
12

E_ALL

All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)

8191

All the above error level can be set using following PHP built-in pbrary function where level cab be any of the value defined in above table.

int error_reporting ( [int $level] )

Following is the way you can create one error handpng function −

<?php
   function handleError($errno, $errstr,$error_file,$error_pne) {
      echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_pne";
      echo "<br />";
      echo "Terminating PHP Script";
      
      die();
   }
?>

Once you define your custom error handler you need to set it using PHP built-in pbrary set_error_handler function. Now lets examine our example by calpng a function which does not exist.

<?php
   error_reporting( E_ERROR );
   
   function handleError($errno, $errstr,$error_file,$error_pne) {
      echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_pne";
      echo "<br />";
      echo "Terminating PHP Script";
      
      die();
   }
   
   //set error handler
   set_error_handler("handleError");
   
   //trigger error
   myFunction();
?>

Exceptions Handpng

PHP 5 has an exception model similar to that of other programming languages. Exceptions are important and provides a better control over error handpng.

Lets explain there new keyword related to exceptions.

    Try − A function 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.

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ...

    An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block.

    Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions.

    Exceptions can be thrown (or re-thrown) within a catch block.

Example

Following is the piece of code, copy and paste this code into a file and verify the result.

<?php
   try {
      $error =  Always throw this error ;
      throw new Exception($error);
      
      // Code following an exception is not executed.
      echo  Never executed ;
   }catch (Exception $e) {
      echo  Caught exception:  ,  $e->getMessage(), "
";
   }
   
   // Continue execution
   echo  Hello World ;
?>

In the above example $e->getMessage function is used to get error message. There are following functions which can be used from Exception class.

    getMessage() − message of exception

    getCode() − code of exception

    getFile() − source filename

    getLine() − source pne

    getTrace() − n array of the backtrace()

    getTraceAsString() − formated string of trace

Creating Custom Exception Handler

You can define your own custom exception handler. Use following function to set a user-defined exception handler function.

string set_exception_handler ( callback $exception_handler )

Here exception_handler is the name of the function to be called when an uncaught exception occurs. This function must be defined before calpng set_exception_handler().

Example

<?php
   function exception_handler($exception) {
      echo "Uncaught exception: " , $exception->getMessage(), "
";
   }
	
   set_exception_handler( exception_handler );
   throw new Exception( Uncaught Exception );
   
   echo "Not Executed
";
?>

Check complete set of error handpng functions at PHP Error Handpng Functions

Advertisements