PHP Exception handling error handling

Source: Internet
Author: User
Tags php exception handling stack trace

1. What is an exception?

An exception is an unexpected condition caused by an external environment in the program's operation, which causes the program to fail to follow the normal process.

2. PHP exception handling mechanism

Exceptions generated in PHP code can be thrown by a throw statement and captured by a catch statement. The code that requires exception handling must be placed inside a try code block to catch possible exceptions. Each try must have at least one catch corresponding to it.

try{

Code with errors or exceptions that may occur

} catch (Exception $e) {

For exception handling, method:

1, self-treatment

2. Do not process, throw it again

}

handling of exceptions after capture : 1 The exception information is saved to the database for programs that are executed more than once.

2 debugging phase can output stack information to quickly identify problems,

try {

throw new Exception (' a Exception ');

} catch (Exception $e) {

echo "MESSAGE =". $e->getmessage (). "\ n". "STACK TRACE = \ n". $e->gettraceasstring ();

}

3 output exception information after publishing.

try {

throw new Exception (' a Exception ');

} catch (Exception $e) {

echo "MESSAGE =". $e->getmessage ();

}

Use multiple Catch You can capture the exceptions that are generated by different classes.

<?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);

}

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 ();

}

?>

When the try code block no longer throws an exception or cannot find a catch that matches the thrown exception, the PHP code resumes execution after jumping to the last catch. Of course, PHP allows you to throw (throw) exceptions again within a catch code block. When an exception is thrown, the code behind the block that throws the exception will not continue, and PHP will attempt to find the first catch to match it.

If an exception is not captured, you can use the Set_exception_handler () must define an exception handler function $exception_handler before the exception is thrown and use

Set_exception_handler ($exception _handler) is set to the default exception handler for exceptions that are not captured with try/catch blocks. Example:

<?php

function Exception_handler ($exception) {

echo "uncaught exception:", $exception->getmessage (), "\ n";

}

Set_exception_handler (' Exception_handler ');

throw new Exception (' an Exception ');

?>

The above program output is: uncaught Exception:an exception

If the exception is not captured and is not used Set_exception_handler () for the corresponding treatment

so PHP will produce a serious error and output uncaught Exception ... (The exception is not caught) prompt information.

As follows:

<?php

throw new Exception (' an Exception ');

?>

Above program output: Fatal error:uncaught exception ' exception ' with message ' a exception ' in D:\xampp\htdocs\woo\exception\1.php:2 S Tack Trace: #0 {main} thrown in D:\xampp\htdocs\woo\exception\1.php on line 2

3.Zendframework How to handle exceptions

Zend_controller_front will catch all exceptions and register to the response object by default, and the response object will not display the exception message by default.

By default, the error handler plug-in (handler plugin) will be registered and activated. It acts as a postdispatch () plug-in to check whether the dispatcher, action controller, or other exception occurred. The exception fetch is recorded in an object, and the object is registered in the request. Use Zend_controller_action::_getparam (' Error_Handler ') to read it. If an exception occurs, it will turn to an error handling controller errorcontroller::erroraction (). The exception is triggered by the error manager by grabbing the exception property of the Error_Handler object.

Public Function ErrorAction ()

{

Get Error_Handler Object

$errors = $this->_getparam (' Error_Handler ');

Switch ($errors->type) {

Case Zend_controller_plugin_errorhandler::exception_no_controller:

Case Zend_controller_plugin_errorhandler::exception_no_action:

$this->getresponse ()->sethttpresponsecode (404);

Break

Default

Application Error

$this->getresponse ()->sethttpresponsecode (500);

Break

}

Get exception

$exception = $errors->exception;

The exception handling is transmitted to the view output or saved to the database according to different conditions.

}

4 . PHP error handling mechanism

In PHP, the default error handling is simple. A message is sent to the browser with a file name, line number, and a message that describes the error.

For example

<?php

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

?>

The result is: Warning:fopen (welcome.txt): Failed to open stream:no such file or directory in D:\xampp\htdocs\woo\error\2.php on Li NE 2

Basic error handling: Using Die () function

<?php

if (!file_exists ("Welcome.txt"))

{

Die ("File not Found");

}

Else

{

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

}

?>

Terminates the script and loses the custom information after the error.

Create a custom error handler

Create a function that handles errors first, which must be capable of handling at least two parameters (Error level and error message), but can accept up to five parameters (optional: File, Line-number, and error context)

Function ErrorHandler ($errNo, $ERRMSG) {

echo "<b>Error:</b> [$errNo] $errMsg <br/>";

echo "Ending Script";

Die ();

}

Use Set_error_handler to set ErrorHandler as the error handler.

<?php

Function ErrorHandler ($errNo, $ERRMSG) {

echo "<b>Error:</b> [$errNo] $errMsg <br/>";

echo "Ending Script";

Die ();

}

Set_error_handler ("ErrorHandler");

$test = 2;

if ($test >1)

{

Trigger Error

Trigger_error ("Value must be 1 or below", e_user_warning);

}

?>

Output: Error: [+] Value must be 1 or below

Ending Script

You can also host the error message to Errorexception in the error handling function, and then process it.

function Errorexceptionhandler ($errNo, $ERRMSG, $errFile, $errLine)

{

       if ( In_array ($errNo, Array (E_user_error, E_error))) {

               throw new Errorexception ($ERRMSG, 0, $errNo, $errFile, $errLine);

      }

       return false;

}

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.