📄 php_exception.asp
字号:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PHP Exception Handling</title>
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<meta name="Keywords" content="xml,tutorial,html,dhtml,css,xsl,xhtml,javascript,asp,ado,vbscript,dom,sql,colors,soap,php,authoring,programming,training,learning,beginner's guide,primer,lessons,school,howto,reference,examples,samples,source code,tags,demos,tips,links,FAQ,tag list,forms,frames,color table,w3c,cascading style sheets,active server pages,dynamic html,internet,database,development,Web building,Webmaster,html guide" />
<meta name="Description" content="Free HTML XHTML CSS JavaScript DHTML XML DOM XSL XSLT RSS AJAX ASP ADO PHP SQL tutorials, references, examples for web building." />
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<link rel="stylesheet" type="text/css" href="../stdtheme.css" />
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "../../https@ssl./default.htm" : "../../www./default.htm");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-3855518-1");
pageTracker._initData();
pageTracker._trackPageview();
</script>
</head>
<body>
<a name="top"></a>
<table cellpadding="0" cellspacing="0" width="100%" bgcolor="#808080">
<tr>
<td width="234" valign="top">
<a href="../default.htm"><img src="../images/w3default80.jpg" border="0" alt="W3Schools" /></a>
</td>
<th valign="middle" align="left" class="right">
<script type="text/javascript"><!--
google_ad_client = "pub-3440800076797949";
/*txtimg*/
google_ad_slot = "5330033957";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript" src="../../pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<noscript>
<a href="../default.asp" target="_blank"><img src="../banners/w6.gif" border="0" alt="W3Schools" /></a>
</noscript>
<br /></th>
</tr>
</table>
<table style="margin-left:1px" width="800px" border="0" cellpadding="0" cellspacing="2">
<tr>
<td width="137" class="content" valign="top"><br />
<a class="left" href="../default.asp" target="_top">
<img src="../images/homeicon.gif" border="0" alt="home" /></a>
<a class="left" href="../default.asp" target="_top">
<b>HOME</b></a>
<br /><br />
<b>PHP Basic</b><br />
<a class="left" target="_top" href="default.asp" >PHP HOME</a><br />
<a class="left" target="_top" href="php_intro.asp" >PHP Intro</a><br />
<a class="left" target="_top" href="php_install.asp" >PHP Install</a><br />
<a class="left" target="_top" href="php_syntax.asp" >PHP Syntax</a><br />
<a class="left" target="_top" href="php_variables.asp" >PHP Variables</a><br />
<a class="left" target="_top" href="php_string.asp" >PHP String</a><br />
<a class="left" target="_top" href="php_operators.asp" >PHP Operators</a><br />
<a class="left" target="_top" href="php_if_else.asp" >PHP If...Else</a><br />
<a class="left" target="_top" href="php_switch.asp" >PHP Switch</a><br />
<a class="left" target="_top" href="php_arrays.asp" >PHP Arrays</a><br />
<a class="left" target="_top" href="php_looping.asp" >PHP Looping</a><br />
<a class="left" target="_top" href="php_functions.asp" >PHP Functions</a><br />
<a class="left" target="_top" href="php_forms.asp" >PHP Forms</a><br />
<a class="left" target="_top" href="php_get.asp" >PHP $_GET</a><br />
<a class="left" target="_top" href="php_post.asp" >PHP $_POST</a><br />
<br />
<b>PHP Advanced</b><br />
<a class="left" target="_top" href="php_date.asp" >PHP Date</a><br />
<a class="left" target="_top" href="php_includes.asp" >PHP Include</a><br />
<a class="left" target="_top" href="php_file.asp" >PHP File</a><br />
<a class="left" target="_top" href="php_file_upload.asp" >PHP File Upload</a><br />
<a class="left" target="_top" href="php_cookies.asp" >PHP Cookies</a><br />
<a class="left" target="_top" href="php_sessions.asp" >PHP Sessions</a><br />
<a class="left" target="_top" href="php_mail.asp" >PHP E-mail</a><br />
<a class="left" target="_top" href="php_secure_mail.asp" >PHP Secure E-mail</a><br />
<a class="left" target="_top" href="php_error.asp" >PHP Error</a><br />
<a class="left" target="_top" href="php_exception.asp" style='font-weight:bold;'>PHP Exception</a><br />
<a class="left" target="_top" href="php_filter.asp" >PHP Filter</a><br />
<br />
<b>PHP Database</b><br />
<a class="left" target="_top" href="php_mysql_intro.asp" >MySQL Introduction</a><br />
<a class="left" target="_top" href="php_mysql_connect.asp" >MySQL Connect</a><br />
<a class="left" target="_top" href="php_mysql_create.asp" >MySQL Create</a><br />
<a class="left" target="_top" href="php_mysql_insert.asp" >MySQL Insert</a><br />
<a class="left" target="_top" href="php_mysql_select.asp" >MySQL Select</a><br />
<a class="left" target="_top" href="php_mysql_where.asp" >MySQL Where</a><br />
<a class="left" target="_top" href="php_mysql_order_by.asp" >MySQL Order By</a><br />
<a class="left" target="_top" href="php_mysql_update.asp" >MySQL Update</a><br />
<a class="left" target="_top" href="php_mysql_delete.asp" >MySQL Delete</a><br />
<a class="left" target="_top" href="php_db_odbc.asp" >PHP ODBC</a><br />
<br />
<b>PHP XML</b><br />
<a class="left" target="_top" href="php_xml_parser_expat.asp" >XML Expat Parser</a><br />
<a class="left" target="_top" href="php_xml_dom.asp" >XML DOM</a><br />
<a class="left" target="_top" href="php_xml_simplexml.asp" >XML SimpleXML</a><br />
<br />
<b>PHP and AJAX</b><br />
<a class="left" target="_top" href="php_ajax_intro.asp" >AJAX Introduction</a><br />
<a class="left" target="_top" href="php_ajax_xmlhttprequest.asp" >XMLHttpRequest</a><br />
<a class="left" target="_top" href="php_ajax_suggest.asp" >AJAX Suggest</a><br />
<a class="left" target="_top" href="php_ajax_xml.asp" >AJAX XML</a><br />
<a class="left" target="_top" href="php_ajax_database.asp" >AJAX Database</a><br />
<a class="left" target="_top" href="php_ajax_responsexml.asp" >AJAX responseXML</a><br />
<a class="left" target="_top" href="php_ajax_livesearch.asp" >AJAX Live Search</a><br />
<a class="left" target="_top" href="php_ajax_rss_reader.asp" >AJAX RSS Reader</a><br />
<a class="left" target="_top" href="php_ajax_poll.asp" >AJAX Poll</a><br />
<br />
<b>PHP Reference</b><br />
<a class="left" target="_top" href="php_ref_array.asp" >PHP Array</a><br />
<a class="left" target="_top" href="php_ref_calendar.asp" >PHP Calendar</a><br />
<a class="left" target="_top" href="php_ref_date.asp" >PHP Date</a><br />
<a class="left" target="_top" href="php_ref_directory.asp" >PHP Directory</a><br />
<a class="left" target="_top" href="php_ref_error.asp" >PHP Error</a><br />
<a class="left" target="_top" href="php_ref_filesystem.asp" >PHP Filesystem</a><br />
<a class="left" target="_top" href="php_ref_filter.asp" >PHP Filter</a><br />
<a class="left" target="_top" href="php_ref_ftp.asp" >PHP FTP</a><br />
<a class="left" target="_top" href="php_ref_http.asp" >PHP HTTP</a><br />
<a class="left" target="_top" href="php_ref_libxml.asp" >PHP Libxml</a><br />
<a class="left" target="_top" href="php_ref_mail.asp" >PHP Mail</a><br />
<a class="left" target="_top" href="php_ref_math.asp" >PHP Math</a><br />
<a class="left" target="_top" href="php_ref_misc.asp" >PHP Misc</a><br />
<a class="left" target="_top" href="php_ref_mysql.asp" >PHP MySQL</a><br />
<a class="left" target="_top" href="php_ref_simplexml.asp" >PHP SimpleXML</a><br />
<a class="left" target="_top" href="php_ref_string.asp" >PHP String</a><br />
<a class="left" target="_top" href="php_ref_xml.asp" >PHP XML</a><br />
<a class="left" target="_top" href="php_ref_zip.asp" >PHP Zip</a><br />
<br />
<b>PHP Quiz</b><br />
<a class="left" target="_top" href="php_quiz.asp" >PHP Quiz</a><br />
<!--<b>PHP XML</b><br />
<a class="left" target="_top" href="php_xml_parser.asp" >PHP Expat</a><br />
<a class="left" target="_top" href="php_xml.asp" >PHP XML</a><br />
<br />
<b>PHP Software</b><br />
<a class="left" target="_top" href="php_zend.asp" >Zend Studio</a><br />
--><br />
<b>Selected Reading</b><br />
<a class="left" target="_top" href="../browsers/browsers_stats.asp">Web Statistics</a><br />
<a class="left" target="_top" href="../site/site_glossary.asp">Web Glossary</a><br />
<a class="left" target="_top" href="../hosting/default.asp">Web Hosting</a><br />
<a class="left" target="_top" href="../quality/default.asp">Web Quality</a><br /><br />
<a class="left" target="_top" href="../forum/default.asp">W3Schools Forum</a><br /><br />
<a class="left" target="_top" href="../about/about_helping.asp">Helping W3Schools</a><br /><br />
<script type="text/javascript"><!--
google_ad_client = "pub-3440800076797949";
/*LeftLinkUnit*/
google_ad_slot = "4854527104";
google_ad_width = 120;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="../../pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</td>
<td valign="top">
<table style="border: 1px solid gray" width="100%" bgcolor="#FFFFFF" border="0" cellpadding="5" cellspacing="0">
<tr>
<td>
<h1>PHP Exception Handling</h1>
<a href="php_error.asp"><img alt="previous" border="0" src="../images/btn_previous.gif" width="100" height="20" /></a>
<a href="php_filter.asp"><img alt="next" border="0" src="../images/btn_next.gif" width="100" height="20" /></a>
<hr />
<p class="intro">Exceptions are used to change the normal flow of a script if a
specified error occurs</p>
<hr />
<h2>What is an Exception</h2>
<p>With PHP 5 came a new object oriented way of dealing with errors.</p>
<p>Exception handling is used to change the normal flow of the code execution if
a specified error (exceptional) condition occurs. This condition is called an
exception.<br />
<br />
This is what normally happens when an exception is triggered:</p>
<ul>
<li>The current code state is saved</li>
<li>The code execution will switch to a predefined (custom) exception
handler function</li>
<li>Depending on the situation, the handler may then resume the execution
from the saved code state, terminate the script execution or continue the
script from a different location in the code</li>
</ul>
<p>We will show different error handling methods:</p>
<ul>
<li>Basic use of Exceptions</li>
<li>Creating a custom exception handler</li>
<li>Multiple exceptions</li>
<li>Re-throwing an exception</li>
<li>Setting a top level exception handler</li>
</ul>
<p><b>Note:</b> Exceptions should only be used with error conditions, and should not be used
to jump to another place in the code at a specified point.</p>
<hr />
<h2>Basic Use of Exceptions</h2>
<p>When an exception is thrown, the code following it will not be executed, and
PHP will try to find the matching "catch" block.</p>
<p>If an exception is not caught, a fatal error will be issued with an "Uncaught
Exception" message.</p>
<p>Lets try to throw an exception without catching it:</p>
<table width="100%" border="1" class="ex" cellspacing="0" id="table42"><tr><td>
<pre><?php
//create function with an exception
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception
checkNum(2);
?></pre>
</td></tr></table>
<p>The code above will get an error like this:</p>
<table width="100%" border="1" class="ex" cellspacing="0" id="table43"><tr><td>
<pre><b>Fatal error</b>: Uncaught exception 'Exception'
with message 'Value must be 1 or below' in C:\webfolder\test.php:6
Stack trace: #0 C:\webfolder\test.php(12):
checkNum(28) #1 {main} thrown in <b>C:\webfolder\test.php</b> on line <b>6</b></pre>
</td></tr></table>
<h2>Try, throw and catch</h2>
<p>To avoid the error from the example above, we need to create the proper code
to handle an exception. </p>
<p>Proper exception code should include:</p>
<ol>
<li>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"</li>
<li>Throw - This is how you trigger an exception. Each "throw" must have at
least one "catch"</li>
<li>Catch - A "catch" block retrieves an exception and creates an object
containing the exception information</li>
</ol>
<p>Lets try to trigger an exception with valid code:</p>
<table width="100%" border="1" class="ex" cellspacing="0" id="table15"><tr><td>
<pre><?php
//create function with an exception
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception in a "try" block
try
{
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}
//catch exception
catch(Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
?></pre>
</td></tr></table>
<p>The code above will get an error like this:</p>
<table width="100%" border="1" class="ex" cellspacing="0" id="table14"><tr><td>
<pre>Message: Value must be 1 or below</pre>
</td></tr></table>
<h2>Example explained:</h2>
<p>The code above throws an exception and catches it:</p>
<ol>
<li>The checkNum() function is created. It checks if a number is greater
than 1. If it is, an exception is thrown</li>
<li>The checkNum() function is called in a "try" block</li>
<li>The exception within the checkNum() function is thrown</li>
<li>The "catch" block retrives the exception and creates an object ($e)
containing the exception information</li>
<li>The error message from the exception is echoed by calling $e->getMessage()
from the exception object</li>
</ol>
<p>However, one way to get around the "every throw must have a catch" rule is to
set a top level exception handler to handle errors that slip through.</p>
<hr />
<h2>Creating a Custom Exception Class</h2>
<p>Creating a custom exception handler is quite simple. We simply 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.</p>
<p>The custom exception class inherits the properties from PHP's
exception class and you can add custom functions to it.</p>
<p>Lets create an exception class:</p>
<table class="ex" cellspacing="0" border="1" width="100%" id="table24">
<tr>
<td>
<pre><?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}</pre>
<pre>$email = "someone@example...com";</pre>
<pre>try
{
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
//throw exception if email is not valid
throw new customException($email);
}
}</pre>
<pre>catch (customException $e)
{
//display custom message
echo $e->errorMessage();
}
?></pre>
</td>
</tr>
</table>
<p>The new class is a copy of the old exception class with an addition of the
errorMessage() function. Since it is a copy of the old class, and it inherits
the properties and methods from the old class, we can use the exception class
methods like getLine() and getFile() and getMessage().</p>
<h2>Example explained:</h2>
<p>The code above throws an exception and catches it with a custom exception
class:</p>
<ol>
<li>The customException() class is created as an extension of the old
exception class. This way it inherits all methods and properties from the
old exception class</li>
<li>The errorMessage() function is created. This function returns an error
message if an e-mail address is invalid</li>
<li>The $email variable is set to a string that is not a valid e-mail
address</li>
<li>The "try" block is executed and an exception is thrown since
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -