PHP的Try, throw 和 catch简单用法
本文简单记录一下关于php中的 Try, throw 和 catch 的用法,后面有时间再做一个详细的解析。
Try - 使用异常的函数应该位于 "try" 代码块内。如果没有触发异常,则代码将照常继续执行。但是如果异常被触发,会抛出一个
异常。
Throw - 这里规定如何触发异常。每一个 "throw" 必须对应至少一个 "catch"
Catch - "catch" 代码块会捕获异常,并创建一个包含异常信息的对象
让我们触发一个异常:
<?php //创建可抛出一个异常的函数 function checkNum($number){ if($number>1){ throw new Exception("Value must be 1 or below"); } return true; } //在 "try" 代码块中触发异常 try{ checkNum(2); //捕获异常 }catch(Exception $e){ echo 'Message: ' .$e->getMessage(); }
上面代码将获得类似这样一个错误:
Message: Value must be 1 or below
例子解释:
上面的代码抛出了一个异常,并捕获了它:
创建 checkNum() 函数。它检测数字是否大于 1。如果是,则抛出一个异常。
在 "try" 代码块中调用 checkNum() 函数。
checkNum() 函数中的异常被抛出
"catch" 代码块接收到该异常,并创建一个包含异常信息的对象 ($e)。
通过从这个 exception 对象调用 $e->getMessage(),输出来自该异常的错误消息,不过,为了遵循“每个 throw 必须对应一个
catch 的原则,可以设置一个顶层的异常处理器来处理漏掉的错误。
您可能感兴趣的文章
- php通过socket获取网页内容的简单示例
- php提示PHP Warning: date(): It is not safe to rely on the......错误的解决办法
- php中$this、static、final、const、self 等几个关键字的用法
- phpMyAdmin Cannot start session without errors错误解决办法
- windows下memcache的安装与配置教程
- 发送邮件SMTP Error Could not connect to SMTP host. send fail的解决办法
- PHP中file_get_contents于curl性能效率比较
- PHP连接、操纵Memcached的原理和教程

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version
Visual web development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools
