Home Backend Development PHP Tutorial PHP的异常处理类Exception的使用及说明_PHP

PHP的异常处理类Exception的使用及说明_PHP

Jun 01, 2016 pm 12:11 PM
exception

1、首先php5提供了基本的异常处理类,可直接使用
复制代码 代码如下:
class Exception
{
protected $message = 'Unknown exception'; // 异常信息
protected $code = 0; // 用户自定义异常代码
protected $file; // 发生异常的文件名
protected $line; // 发生异常的代码行号
function __construct($message = null, $code = 0);
final function getMessage(); // 返回异常信息
final function getCode(); // 返回异常代码
final function getFile(); // 返回发生异常的文件名
final function getLine(); // 返回发生异常的代码行号
final function getTrace(); // backtrace() 数组
final function getTraceAsString(); // 已格成化成字符串的 getTrace() 信息
/* 可重载的方法 */
function __toString(); // 可输出的字符串
}
?>

简单的使用如下:(通过异常,抛出错误信息)
复制代码 代码如下:
try {
$error = 'my error!';
throw new Exception($error)
} catch (Exception $e) {
echo $e->getMessage();
}

2、我们可以扩展此类,方便我们的使用
复制代码 代码如下:
class MyException extends Exception
{
// 重定义构造器使 message 变为必须被指定的属性
public function __construct($message, $code = 0) {
// 自定义的代码
// 确保所有变量都被正确赋值
parent::__construct($message, $code);
}
// 自定义字符串输出的样式
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
public function customFunction() {
echo "A Custom function for this type of exception\n";
}
}

异常处理的基本思想是代码在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()    —返回产生异常的代码所在的行。

注意:
当捕获到一个异常后,try()块里面的后续代码将不会继续执行,而是会尝试查找匹配的“catch”代码块
当抛出一个异常后,如果不进行catch处理,则会报“Uncaught exception 'Exception'”错误
复制代码 代码如下:
function test($val){
if ($val>100){
throw new Exception("提示信息:您输入的值过大");
}
}
test(111);
?>

3.当一个异常抛出后,catch语句块可以进行处理也可以不处理
以下是我用户注册功能的部分代码
复制代码 代码如下:
try{
//check forms filled in
if(!filled_out($_POST)){
throw new Exception('你还没有填写表单,请回去填写');
}
//check email address not valid
if(!check_email($email)){
throw new Exception('邮件的格式不正确');
}
//检查密度的长度是否大于6
if(strlen($passwdthrow new Exception('密度的长度应该大于6');
}
//检查两次密码是否相等
if($passwd!=$passwd1){
throw new Exception('两次密码不一样,请重新输入');
}
//检查用户名的长度是否正确
if(strlen($username)>16){
throw new Exception('用户名的长度不符,请重新输入');
}
} catch(Exception $e){
echo $e->getMessage(); //输出异常信息。
}

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Causes and solutions to ConcurrentModificationException exceptions in Java Causes and solutions to ConcurrentModificationException exceptions in Java Jun 25, 2023 am 10:33 AM

In Java, when multiple threads operate a collection object at the same time, a ConcurrentModificationException exception may occur. This exception usually occurs when traversing the collection when modifying or deleting elements. This will cause the state of the collection to be inconsistent, thus throwing abnormal. This article will delve into the causes and solutions to this exception. 1. Causes of Exception Normally, ConcurrentModificationException exception

Solution to PHP Fatal error: Uncaught exception 'PDOException' Solution to PHP Fatal error: Uncaught exception 'PDOException' Jun 23, 2023 pm 12:09 PM

In PHP development, you may encounter errors such as "PHPFatalerror:Uncaughtexception'PDOException'". This is an exception caused by an error when PHP operates the database. If this error is not handled in time, it will cause program interruption or unexpected errors. So how to solve this problem? Here are some common solutions. 1. Check the database parameters. First, we need to check the parameters passed when connecting to the database.

How to deal with UnsupportedEncodingException in Java? How to deal with UnsupportedEncodingException in Java? Jun 25, 2023 am 08:02 AM

How to deal with UnsupportedEncodingException in Java? In Java programming, you may encounter UnsupportedEncodingException. This exception is usually caused by incorrect encoding conversion or an unsupported encoding. In this article, we will introduce the causes of UnsupportedEncodingException exception and how to deal with it. What is UnsupportedE

What are the common causes of ConcurrentModificationException in Java? What are the common causes of ConcurrentModificationException in Java? Jun 25, 2023 am 11:07 AM

What are the common causes of ConcurrentModificationException in Java? When traversing a collection using an iterator in the Java collection framework, a ConcurrentModificationException exception is sometimes thrown, which is one of the common Java exceptions. So, what is the reason for this exception? First, we need to understand that the iterators provided by the Java collection framework are stateful. That is, when traversing

Solution to ArrayStoreException exception in Java Solution to ArrayStoreException exception in Java Jun 25, 2023 am 08:05 AM

In Java development, we often use arrays to store a series of data because of the convenience and performance advantages of arrays. However, in the process of using arrays, some exceptions will occur, and one of the common exceptions is ArrayStoreException. This exception is thrown when we store incompatible data types in the array. This article will introduce what an ArrayStoreException is, why it occurs, and how to solve it. 1. Arr

What are the common causes of ArrayStoreException in Java? What are the common causes of ArrayStoreException in Java? Jun 25, 2023 am 09:48 AM

In Java programming, array is an important data structure. Arrays can store multiple values ​​in a single variable, and more importantly each value can be accessed using an index. But while working with arrays, some exceptions may occur, one of them is ArrayStoreException. This article will discuss common causes of ArrayStoreException exceptions. 1. Type mismatch The element type must be specified when the array is created. When we try to store incompatible data types into an array, it throws

In Java, what is the difference between Exception class and Error class? In Java, what is the difference between Exception class and Error class? Sep 09, 2023 pm 12:05 PM

The Exception class and the Error class are both subclasses of the java.lang.Throwable class. We can handle runtime exceptions, but not errors. Exceptions are objects that represent logical errors that occur at runtime, causing the JVM to enter an "ambiguous" state. Objects automatically created by the JVM to represent these runtime errors are called exceptions. Error is a subclass of the Throwable class that indicates serious problems that reasonable applications should not try to catch. Most of these errors are anomalies. If an exception occurs, we can use try and catch blocks to handle it. If an error occurs that we cannot handle, the program will terminate. There are two types of exceptions, one is CheckedExce

Solution to UnsupportedEncodingException exception in Java Solution to UnsupportedEncodingException exception in Java Jun 25, 2023 am 08:48 AM

UnsupportedEncodingException may occur in Java, mainly because the encoding is not supported. When processing text data, it is often necessary to perform encoding conversion, that is, to convert the content of one encoding format into the content of another encoding format. If the encoding type used for encoding conversion is not supported, an UnsupportedEncodingException will be thrown. This article will introduce the solution to this exception. one,

See all articles