php 异常处理

WBOY
Release: 2016-06-23 14:30:01
Original
902 people have browsed it

异常处理的基本思想是代码在try代码被调用执行。如果try码块出现错误,我们可以执行一个抛出异常的处理。某些编程语言,如java,,在特定情况下将自动抛出异常。在php中,异常必须手动抛出。可以使用如下方式抛出一个异常:

Throw new Exception(‘message’,code);

Throw 关键字将触发异常处理机制,它是一个语言结构,而不是一个函数,但是必须给它传递一个值。它要求一个接受对象。在最简单的情况下,可以实例化一个内置的Exception类。

最后,在try代码之后,必须至少给出一个catch代码块。可以将多个catch代码块与一个try代码块进行关联。如果每个catch代码块可以捕获一个不同类型的异常,可以使用多个catch代码块是有意义的。例如,如果想捕获Exception类的异常,代码如下

Catch(Exception $e)

{

   //handing exception

}

Catch代码捕获的对象就是导致异常并传递给throw语句的对象(被throw 语句抛出)。使用Exception 类的实例,是不错的选择。

Exception类提供了如下的内置方法:

Getcode()?返回传递给构造函数的代码。

GetMessage()?返回传递给构造函数的消息。

getFile()?返回产生异常代码的文件的路径

getLine()?返回产生异常的代码所在的行。

 

以下是我用户注册功能的部分代码

查看代码

 1 try{ 2     //check forms filled in 3     if(!filled_out($_POST)){ 4         throw new Exception('你还没有填写表单,请回去填写'); 5     } 6     //check email address not valid 7     if(!check_email($email)){ 8        throw new Exception('邮件的格式不正确'); 9     }10     //检查密度的长度是否大于611     if(strlen($passwd<6)){12         throw new Exception('密度的长度应该大于6');13     }14     //检查两次密码是否相等15     if($passwd!=$passwd1){16         throw new Exception('两次密码不一样,请重新输入');17     }18     //检查用户名的长度是否正确19     if(strlen($username)>16){20         throw new Exception('用户名的长度不符,请重新输入');21     }22   23 } catch(Exception $e){24     echo $e->getMessage(); //输出异常信息。25 }
Copy after login

 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!