编程小贴士

给你的编程提供小点子


PHP错误处理及异常处理

PHP提供了错误处理和日志记录的功能. 这些函数允许你定义自己的错误处理规则,以及修改错误记录的方式. 这样,你就可以根据自己的需要,来更改和加强错误输出信息以满足实际需要.

通过日志记录功能,你可以将信息直接发送到其他日志服务器,或者发送到指定的电子邮箱(或者通过邮件网关发送),或者发送到操作系统日志等,从而可以有选择的记录和监视你的应用程序和网站的最重要的部分。

错误报告功能允许你自定义错误反馈的级别和类型,可以是简单的提示信息或者使用自定义的函数进行处理并返回信息.

为什么要使用错误处理?

 

  • 是网站出错时对用户友好
  • 更好的避免错误、调试、修复错误
  • 避免一些安全风险
  • 更好保证程序的健壮性
  • ……

 

1、最简单的错误处理――die()

当我们预计有错误发生时,停止脚步的运行。比如连接数据库时

1    2

3

 

     mysql_connect(\’localhost\’, \’root\’, \’123456\’)

or die (\’连接数据库错误:\’. mysql_error());

不过,简单地终止脚本并不总是恰当的方式。

2、自定义错误和错误触发器

我们创建一个错误处理专用函数,使用set_error_handler函数设置后,可以在 PHP 中发生错误时调用该函数。

定义错误处理函数的参数

参数 描述
error_level 必需。为用户定义的错误规定错误报告级别。必须是一个值数。     参见下面的表格:错误报告级别。
error_message 必需。为用户定义的错误规定错误消息。
error_file 可选。规定错误在其中发生的文件名。
error_line 可选。规定错误发生的行号。
error_context 可选。规定一个数组,包含了当错误发生时在用的每个变量以及它们的值。

错误基本预定义常量

错误和日志记录

常量 说明 备注
1 E_ERROR (integer) 致命的运行时错误。这类错误一般是不可恢复的情况,例如内存分配导致的问题。后果是导致脚本终止不再继续运行。
2 E_WARNING (integer) 运行时警告 (非致命错误)。仅给出提示信息,但是脚本不会终止运行。
4 E_PARSE (integer) 编译时语法解析错误。解析错误仅仅由分析器产生。
8 E_NOTICE (integer) 运行时通知。表示脚本遇到可能会表现为错误的情况,但是在可以正常运行的脚本里面也可能会有类似的通知。
16 E_CORE_ERROR (integer) 在PHP初始化启动过程中发生的致命错误。该错误类似 E_ERROR,但是是由PHP引擎核心产生的。 since PHP 4
32 E_CORE_WARNING (integer) PHP初始化启动过程中发生的警告 (非致命错误) 。类似 E_WARNING,但是是由PHP引擎核心产生的。 since PHP 4
64 E_COMPILE_ERROR (integer) 致命编译时错误。类似E_ERROR, 但是是由Zend脚本引擎产生的。 since PHP 4
128 E_COMPILE_WARNING (integer) 编译时警告 (非致命错误)。类似 E_WARNING,但是是由Zend脚本引擎产生的。 since PHP 4
256 E_USER_ERROR (integer) 用户产生的错误信息。类似 E_ERROR, 但是是由用户自己在代码中使用PHP函数 trigger_error()来产生的。 since PHP 4
512 E_USER_WARNING (integer) 用户产生的警告信息。类似 E_WARNING, 但是是由用户自己在代码中使用PHP函数 trigger_error()来产生的。 since PHP 4
1024 E_USER_NOTICE (integer) 用户产生的通知信息。类似 E_NOTICE, 但是是由用户自己在代码中使用PHP函数 trigger_error()来产生的。 since PHP 4
2048 E_STRICT (integer) 启用 PHP 对代码的修改建议,以确保代码具有最佳的互操作性和向前兼容性。 since PHP 5
4096 E_RECOVERABLE_ERROR (integer) 可被捕捉的致命错误。 它表示发生了一个可能非常危险的错误,但是还没有导致PHP引擎处于不稳定的状态。 如果该错误没有被用户自定义句柄捕获 (参见 set_error_handler()),将成为一个 E_ERROR 从而脚本会终止运行。 since PHP 5.2.0
8192 E_DEPRECATED (integer) 运行时通知。启用后将会对在未来版本中可能无法正常工作的代码给出警告。 since PHP 5.3.0
16384 E_USER_DEPRECATED (integer) 用户产少的警告信息。 类似 E_DEPRECATED, 但是是由用户自己在代码中使用PHP函数 trigger_error()来产生的。 since PHP 5.3.0
30719 E_ALL (integer) E_STRICT出外的所有错误和警告信息。 30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previously

(级别E_ERROR、E_USER_ERROR不能被自定义错误处理函数扑捉到)自定义错误函数中不能扑捉到致命错误信息,因为发生致命的运行时错误时脚本都是立即停止执行的。

触发错误

在脚本中用户输入数据的位置,当用户的输入无效时触发错误的很有用的。在 PHP 中,这个任务由 trigger_error() 完成。

您可以在脚本中任何位置触发错误,通过添加的第二个参数,您能够规定所触发的错误级别。

可能的错误类型:

 

  • E_USER_ERROR – 致命的用户生成的 run-time 错误。错误无法恢复。脚本执行被中断。
  • E_USER_WARNING – 非致命的用户生成的 run-time 警告。脚本执行不被中断。
  • E_USER_NOTICE – 默认。用户生成的 run-time 通知。脚本发现了可能的错误,也有可能在脚本运行正常时发生。

 

例如:

1    2

 

trigger_error(“出错了啊”, E_USER_WARNING);     // 输出 Warning: 出错了啊 in xxxx 的错误信息

3、错误报告

默认地,根据在 php.ini 中的 error_log 配置,PHP 向服务器的错误记录系统或文件发送错误记录。

通过使用 error_log() 函数,您可以向指定的文件或远程目的地发送错误记录。比如把错误信息发送到邮箱中是一种好的方式。

更多错误处理文档见:http://www.php.net/manual/zh/book.errorfunc.php

4、异常处理

当异常被抛出时,其后的代码不会继续执行,PHP 会尝试查找匹配的 “catch” 代码块。

如果异常没有被捕获,而且又没用使用 set_exception_handler() 作相应的处理的话,那么将发生一个严重的错误(致命错误),并且输出 “Uncaught Exception” (未捕获异常)的错误消息。

处理处理程序应当包括:

 

  • try – 使用异常的函数应该位于 “try” 代码块内。如果没有触发异常,则代码将照常继续执行。但是如果异常被触发,会抛出一个异常。
  • throw – 这里规定如何触发异常。每一个 “throw” 必须对应至少一个 “catch”
  • catch – “catch” 代码块会捕获异常,并创建一个包含异常信息的对象

 

重新抛出异常

有时,当异常被抛出时,您也许希望以不同于标准的方式对它进行处理。可以在一个 “catch” 代码块中再次抛出异常。

脚本应该对用户隐藏系统错误。对程序员来说,系统错误也许很重要,但是用户对它们并不感兴趣。为了让用户更容易使用,您可以再次抛出带有对用户比较友好的消息的异常。

异常的规则

需要进行异常处理的代码应该放入 try 代码块内,以便捕获潜在的异常。

每个 try 或 throw 代码块必须至少拥有一个对应的 catch 代码块。

使用多个 catch 代码块可以捕获不同种类的异常。

可以在 try 代码块内的 catch 代码块中再次抛出(re-thrown)异常。

简而言之:如果抛出了异常,就必须捕获它。

127 Responses to “ PHP错误处理及异常处理 ”

  1. suba me说道:

    qUYwXr Very good article.Really thank you! Much obliged.

  2. Louis Vuitton Monogram Galliera Pm Handbag Bag

  3. Tattoo Shop说道:

    You have made some decent points there. I checked on the internet for additional information about the issue and found most individuals will go along with your views on this site.

  4. Tattoo Artists说道:

    I really liked your blog.Really looking forward to read more. Really Cool.

  5. xem tu vi说道:

    Sources Wow! Thank you! I always needed to write on my blog something like that. Can I take a fragment of your post to my website?

  6. coloring page说道:

    you will have an ideal weblog right here! would you like to make some invite posts on my blog?

  7. Lung Detox说道:

    Im obliged for the article.Really looking forward to read more. Much obliged.

  8. There is apparently a bunch to identify about this. I assume you made various good points in features also.

  9. Spot on with this write-up, I honestly think this web site needs far more attention. I all probably be returning to read more, thanks for the advice!

  10. stiri interesante si utile postate pe blogul dumneavoastra. dar ca si o paranteza , ce parere aveti de cazarea la particulari ?.

  11. You have remarked very interesting points ! ps nice site. аАа’аАТ‚аЂТ˜We are always lucky, a I said and like a fool I did not knock on wood. by Ernest Hemingway.

  12. Thanks for the post.Much thanks again. Great.

  13. Click to read说道:

    wow, awesome blog article.Really looking forward to read more. Awesome.

  14. click here说道:

    You completed a number of fine points there. I did a search on the issue and found most persons will consent with your blog.

  15. site说道:

    This particular blog is really educating additionally diverting. I have discovered helluva interesting stuff out of it. I ad love to go back again soon. Cheers!

  16. Really clear website , appreciate it for this post.

  17. find more info说道:

    There is perceptibly a bunch to realize about this. I feel you made certain nice points in features also.

  18. here说道:

    It as enormous that you are getting thoughts from this post as well as from our argument made at this time.

  19. w88 world说道:

    This is really interesting, You are a very skilled blogger. I ave joined your feed and look forward to seeking more of your excellent post. Also, I ave shared your website in my social networks!

  20. Im thankful for the article post. Really Great.

  21. Wow! This could be one particular of the most useful blogs We ave ever arrive across on this subject. Actually Great. I am also an expert in this topic therefore I can understand your hard work.

  22. woking cab说道:

    This unique blog is really awesome and also factual. I have found helluva interesting tips out of this source. I ad love to return over and over again. Cheers!

  23. Normally I don at learn article on blogs, but I would like to say that this write-up very forced me to check out and do so! Your writing style has been surprised me. Thanks, very great article.

  24. Wow! Thank you! I constantly needed to write on my site something like that. Can I take a fragment of your post to my blog?

  25. Well I found this on Digg, and I like it so I dugg it!

  26. This blog was how do I say it? Relevant!! Finally I have found something that helped me. Thank you!

  27. This website was how do I say it? Relevant!! Finally I ave found something that helped me. Thanks!

  28. status说道:

    Your style is really unique in comparison to other folks I have read stuff from. I appreciate you for posting when you ave got the opportunity, Guess I all just book mark this web site.

  29. see more说道:

    Pierre signe astrologique horoscope septembre balance Here is my homepage; voyance en ligne gratuite

  30. I really liked your blog.Really looking forward to read more. Will read on

  31. The Lost Ways说道:

    Thanks for the article.Really thank you! Cool.

  32. Looking forward to reading more. Great blog article. Awesome.

  33. PERM说道:

    Say, you got a nice blog post.Really thank you! Will read on

  34. Thanks-a-mundo for the blog. Really Great.

  35. Nwokolo Collins说道:

    Thanks-a-mundo for the post.Thanks Again. Great.

  36. Nwokolo说道:

    presses the possibility key for you LOL!

  37. It is best to take part in a contest for among the best blogs on the web. I all recommend this site!

  38. Thank you for your post.Much thanks again. Fantastic.

  39. Very neat article post.Really thank you! Want more.

  40. The Constitution gives every American the inalienable right to make a damn fool of himself..

  41. trash cans说道:

    I value the post.Really thank you! Much obliged.

  42. Beyonce说道:

    It as truly very difficult in this full of activity life to listen news on TV, therefore I simply use internet for that purpose, and take the most recent news.

  43. watch video说道:

    Very interesting subject , thankyou for putting up.

  44. to learn more说道:

    Im grateful for the blog post.Really thank you! Really Great.

  45. truyen ngon tinh说道:

    Perfectly written content, thanks for selective information.

  46. Thank you for your blog.Really looking forward to read more. Really Cool.

  47. Well I definitely enjoyed studying it. This subject provided by you is very constructive for proper planning.

  48. Run on hills to increase your speed. The trailer for the movie

  49. wow, awesome blog article.Thanks Again. Awesome.

  50. thao duoc quy说道:

    What as up, just wanted to say, I enjoyed this article. It was practical. Keep on posting!

  51. Thanks for sharing your info. I truly appreciate your efforts and I am waiting for your next post thank you once again.

  52. Im obliged for the blog post.Thanks Again. Will read on

  53. sidekick说道:

    This website is known as a stroll-by way of for all the information you needed about this and didn?t know who to ask. Glimpse right here, and also you?ll undoubtedly uncover it.

  54. Elena Matei说道:

    There is perceptibly a bunch to know about this. I think you made certain nice points in features also.

  55. visit website说道:

    Really appreciate you sharing this post.Really thank you! Really Great.

  56. David说道:

    Thank You For Your Info. I like to look around the internet, often I will just go to Stumble Upon and follow thru

  57. Im grateful for the blog.Really looking forward to read more. Awesome.

  58. Im thankful for the article post.Thanks Again. Great.

  59. This blog is without a doubt educating as well as factual. I have picked up a lot of interesting stuff out of this amazing blog. I ad love to return again soon. Cheers!

  60. Thank you for your post.Much thanks again. Really Great.

  61. I think this is a real great blog article.Thanks Again. Really Cool.

  62. Thanks a lot for the blog article.Much thanks again. Great.

  63. Thank you ever so for you post.Really thank you! Awesome.

  64. my page说道:

    Thank you for sharing this excellent piece. Very inspiring! (as always, btw)

  65. blue nike说道:

    louis vuitton wallets ??????30????????????????5??????????????? | ????????

  66. worth说道:

    Useful information for all Great remarkable issues here. I am very satisfied to look your article. Thanks a lot and i am taking a look ahead to touch you. Will you kindly drop me a e-mail?

  67. to chuc su kien说道:

    superb post.Ne aer knew this, thanks for letting me know.

  68. Nice blog here! Also your web site loads up very fast! What host are you using? Can I get your affiliate link to your host? I wish my website loaded up as quickly as yours lol

  69. School news说道:

    Wow! Thank you! I continually needed to write on my site something like that. Can I include a part of your post to my site?

  70. School news说道:

    Wohh exactly what I was looking for, thank you for posting.

  71. Thanks for sharing this fine post. Very inspiring! (as always, btw)

  72. In my opinion you are mistaken. I can defend the position.

  73. Incredible points. Outstanding arguments. Keep up the amazing effort.

  74. Please let me know where you got your design. Thanks a

  75. You made some clear points there. I did a search on the subject matter and found most individuals will consent with your website.

  76. Im thankful for the article.Thanks Again.

  77. Open heavens说道:

    not only should your roof protect you from the elements.

  78. tm objection说道:

    I’а†ve read many excellent stuff here. Unquestionably worth bookmarking for revisiting. I surprise how a great deal try you set to create this sort of great informative internet site.

  79. Normally I do not read article on blogs, however I wish to say that this write-up very forced me to check out and do it! Your writing style has been amazed me. Thanks, quite nice article.

  80. That you are my function models. Thank you for your post

  81. Your style is so unique compared to other people I have read stuff from. Many thanks for posting when you ave got the opportunity, Guess I all just book mark this blog.

  82. the original materials to represent skin etc. As for the technology of air cushion; it is useful

  83. Really appreciate you sharing this article.Really looking forward to read more. Really Great.

  84. entclass说道:

    Really enjoyed this article.Really looking forward to read more. Fantastic.

  85. hotels说道:

    Wow, superb blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your site is fantastic, let alone the content!

  86. You are my inhalation , I have few web logs and infrequently run out from to brand.

  87. My brother recommended I might like this blog. He used to be totally right.

  88. What as Happening i am new to this, I stumbled upon this I have found It absolutely helpful and it has aided me out loads. I hope to contribute & assist other users like its helped me. Good job.

  89. Simply wanna say that this is handy, Thanks for taking your time to write this.

  90. visit mokaskita说道:

    below you will find the link to some internet sites that we consider you ought to visit

  91. website not necessarily working precisely clothed in Surveyor excluding stares cool in the field of Chrome. Have any suggestions to aid dose this trouble?

  92. niw说道:

    Im thankful for the blog article.Really thank you! Really Great.

  93. This is my first time go to see at here and i am really impressed to read all at single place.

  94. I was suggested this website by my cousin. I am not sure whether this post is written by him as nobody else know such detailed about my difficulty. You are incredible! Thanks!

  95. iHerb Malaysia说道:

    Very good info. Lucky me I came across your website by chance (stumbleupon). I ave saved it for later!

  96. ban nha di an说道:

    Thanks for every other excellent article. The place else may just anybody get that type of info in such an ideal means of writing? I have a presentation next week, and I am at the look for such info.

  97. My brother suggested I might like this website. He was totally right. This post truly made my day. You can not imagine simply how much time I had spent for this info! Thanks!

  98. Chapel说道:

    Spot on with this write-up, I truly feel this web site needs a lot more attention. I all probably be back again to read more, thanks for the info!

  99. well defined说道:

    Really informative article.Much thanks again. Much obliged.

  100. see more说道:

    I think other web-site proprietors should take this website as an model, very clean and great user genial style and design, let alone the content. You are an expert in this topic!

  101. write for us说道:

    Wow, great article post.Really looking forward to read more.

  102. visit website说道:

    This especially helped my examine, Cheers!

  103. Im grateful for the article post.Much thanks again.

  104. to read more说道:

    Muchos Gracias for your blog post.Thanks Again. Much obliged.

  105. Merely wanna admit that this is very beneficial , Thanks for taking your time to write this.

  106. Major thankies for the article. Want more.

  107. It as difficult to find knowledgeable people in this particular subject, however, you seem like you know what you are talking about! Thanks

  108. ndu说道:

    you ave got a great weblog here! would you like to make some invite posts on my weblog?

  109. It as straight to the point! You could not tell in other words!

  110. classified post说道:

    Thanks for the blog.Much thanks again. Much obliged.

  111. more details说道:

    I will right away snatch your rss feed as I can at to find your email subscription link or e-newsletter service. Do you have any? Please permit me know in order that I could subscribe. Thanks.

  112. Im obliged for the article post.Really looking forward to read more. Keep writing.

  113. Im grateful for the article.Really looking forward to read more. Great.

  114. view说道:

    Pretty! This has been a really wonderful post. Thank you for providing this information.

  115. Wohh exactly what I was looking for, regards for putting up.

  116. cong ty luat说道:

    What as up, I check your new stuff regularly. Your writing style is witty, keep up the good work!

  117. more info说道:

    This is one awesome article post.Really looking forward to read more. Great.

  118. It as nearly impossible to find educated people for this subject, but you seem like you know what you are talking about! Thanks

  119. for more info说道:

    Wow, amazing blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is wonderful, as well as the content!. Thanks For Your article about sex.

  120. wow, awesome blog article.Really thank you! Want more.

  121. MIAMI SEO说道:

    Some genuinely prize content on this web site , saved to my bookmarks.

  122. It as really a great and helpful piece of info. I am glad that you shared this helpful information with us. Please keep us informed like this. Thanks for sharing.

  123. my portfolio说道:

    In my country we don at get any of this kind of article. Need to search around the globe for such quality stuff. I congratulate your effort. Keep it up!

  124. check here说道:

    its really really nice post on building up new website.

  125. good morning说道:

    Not clear on what you have in mind, Laila. Can you give us some more information?

  126. Turban说道:

    You made some nice points there. I did a search on the subject matter and found most persons will approve with your site.

  127. Thanks for a marvelous posting! I definitely enjoyed reading it, you can be a

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>