本文共 1784 字,大约阅读时间需要 5 分钟。
异常处理的基石:try-catch-block
try、catch、throw是PHP中用于处理异常的三大关键字。它们是程序开发中最基础的错误处理机制。通过try-catch结构,可以捕获程序运行过程中出现的异常,采取相应措施进行修复或记录。
1) { throw new Exception("Value must be 1 or below"); } return true;}try { checkNum(2); echo 'If you see this, the number is 1 or below';} catch(Exception $e) { echo 'Message: ' . $e->getMessage();}自定义异常处理:创建专用异常类
除了PHP内置的Exception类,开发者还可以创建自定义异常类。自定义异常类可以包含更多的错误信息,方便 debugging和日志记录。
getLine() . ' in ' . $this->getFile() . ': ' . $this->getMessage() . ' is not a valid E-Mail address'; return $errorMsg; }}$email = "someone@example.com";try { if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { throw new customException($email); }} catch (customException $e) { echo $e->errorMessage();}多个异常捕获:优先处理特定错误
在try-catch结构中,catch语句可以捕获多个异常类型,但需要注意的是,后面的catch必须放在前面的catch之后。这样可以确保优先处理特定异常类型。
getLine() . ' in ' . $this->getFile() . ': ' . $this->getMessage() . ' is not a valid E-Mail address'; return $errorMsg; }}$email = "someone@example.com";try { if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { throw new customException($email); } if(strpos($email, "example") !== FALSE) { throw new Exception("$email is an example e-mail"); }} catch (customException $e) { echo $e->errorMessage();} catch (Exception $e) { echo $e->getMessage();}全局异常处理:set_exception_handler
set_exception_handler函数可以注册一个全局的异常处理函数。无论程序中抛出的异常是否被捕获,都会调用这个函数进行处理。
getMessage();}set_exception_handler('myException');// 以下代码会抛出异常throw new Exception('Uncaught Exception occurred');// 后面的代码不会执行// 输出:Exception: Uncaught Exception occurred触发错误:强制抛出错误
trigger_error函数可以在代码中强制触发错误或异常。这通常用于测试错误处理逻辑或在特定条件下触发预期的错误。
转载地址:http://pptfk.baihongyu.com/