PHP error Handling and PHP exception handling mechanism

Source: Internet
Author: User
Tags define error handling exception handling execution getmessage syslog system log touch

PHP Error Handling

When we develop programs, sometimes there are problems with the program, we can use the following methods to find the error.

Development phase: Output all error reports during development, which will help us to debug the program
Run phase: We do not let the program output any kind of error report (not to allow users to see (including technical, not skilled people))

Write error reports to the log
First, specify error report error_reporting = E_ll
Second, turn off error output Display_errors = Off
Third, turn on error logging function log_errors = On

1. Default if no error log location is specified, the default write Web server log
2. Specify a filename (writable) for the Error_log option
3. Write to the operating system log Error_log=syslog

The following code example

 
  "; 
? >

Of course, PHP also provides a function error_get_last () to get the error message

function definitions and usage

The Error_get_last () function Gets the last occurrence of the error. The function returns the last occurrence of the error as an array. The returned array contains 4 keys and values: [Type]-error type [message]-error messages [file]-Files where the error occurred [line]-where the error occurred

Small example:

 
  Output:
Array ([type] => 8 [message] => Undefined variable:test [file] => D:\www\test.php [line] => 2)
So it's convenient for us ... Is it helpful to debug your program and troubleshoot bugs?

These error reporting levels are different types of errors that the error handlers are designed to handle:

value Constants Description
2 E_warning Non-fatal run-time error. Script execution is not paused.
8 E_notice

Run-time notice.

The script found that an error might occur, but it may also occur when the script is running correctly.

256 E_user_error Fatal user-generated error. This is similar to the e_error that programmers use PHP function Trigger_error () settings.
512 E_user_warning A non-fatal user-generated warning. This is similar to the e_warning that programmers use PHP function Trigger_error () settings.
1024 E_user_notice User-generated notifications. This is similar to the e_notice that programmers use PHP function Trigger_error () settings.
4096 E_recoverable_error A fatal error that can be caught. Similar to E_error, but can be captured by user-defined handlers. (see Set_error_handler ())
8191 E_all

All errors and warnings, except for level e_strict.

(In PHP 6.0,e_strict is part of E_all)

PHP exception handling mechanism

definition:

Exception handling: Unexpected, something that happens in the course of a program's operation, using exceptions to change the script's normal flow

syntax Format:
Try
{//...}
catch (Exception $e)
{//...}

try{}catch{} in PHP is exception handling.

The code to be executed is placed in a try block, and if one of the statements in the execution of the code has an exception, the program jumps directly into the catch block, where the error message and display are collected by $e.

PHP try{}catch{} statement

To further handle the exception, we need to use the PHP try{}catch{}----include the try statement and at least one of the catch statements. Any code that invokes a method that might throw an exception should use a try statement. Catch statements are used to handle exceptions that may be thrown.

Example:

I write a piece of code:

Define an exception class yourself
Function: Write one or more methods to solve the process when this exception occurs
1. Define your own exception class, must be exception (built-in Class) subclasses, you can see the PHP manual inside exception (built-in classes) of the use of
2. Only the construction method and ToString () in the exception class can be overridden, and the others are final

 
  ";
    }
    function open () {Touch
        ("Tmp.txt");

        $file =fopen ("Tmp.txt", "R");

        return $file;
    }
? >

1. If there is no problem with the code in the try, execute it after the catch after it has finished executing
2. If the code in try has an exception, throws an exception object (using throw) and throws it to the parameters in the catch, then the code in the try does not continue to go directly to the catch to execute, execution in the catch is done, and then proceed down
Note: Prompted what the exception, this is not the main we want to do things, need to solve this exception in catch, if not solved, then go out to the user in the following code, if I do not have this TMP.TXT file, it will throw an exception.

If there is an exception, we can resolve the exception by calling the Open method.

 
  GetMessage (). "
"; GetMessage () is a built-in method in PHP that can directly call $file = $e->open (); }

The following code is sorted and multiple exception handling methods:

 -->";

		function open () {Touch ("tmp.txt");

		$file =fopen ("Tmp.txt", "R");
	return $file; The class Demoexception extends Exception {function Pro () {echo] handles the exception that the demo occurred
"; Class TestException extends Exception {function Pro () {echo "handles the exception in test
"; Class Helloexception extends Exception {} class MyClass {function OpenFile () {$file = @fopen ("Tmp.txt", "R"); if (! $file) throw new Openfileexception ("File open failed"); Function demo ($num =0) {if ($num ==1) throw new Demoexception ("demo exception"); The function test ($num =0) {if ($num ==1) throw new TestException ("Test error"); The function fun ($num =0) {if ($num ==1) throw new Helloexception ("###########"); } try{echo "11111111111111
"; $my =new MyClass (); $my->openfile (); $my->demo (0); $my->test (0); $my->fun (1); echo "22222222222222222
"; } catch (Openfileexception $e) {//$e =new Exception (); echo $e->getmessage ().
"; $file = $e->open (); }catch (demoexception $e) {echo $e->getmessage (). "
"; $e->pro (); }catch (testexception $e) {echo $e->getmessage (). "
"; $e->pro (); }catch (Exception $e) {echo $e->getmessage (). "
"; } Var_dump ($file); echo "444444444444444444444
";



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.