php5程序异常处理
异常的工作原理:
try
{
代码处理程序;
if(代码处理发生错误)throw new Exception('抛出一个异常');//使用throw关键字,后面是Exception的一个对象
//需要说明的是php5异常不会自动抛出异常
//抛出异常后下面处理程序不再执行
代码处理程序;
}
catch Exception $e
{
处理异常;
//如:echo 'Exception '.$e->getCode().':'.$e->getMessage().'in'.$e->getFile().'on line'.$e->getLine();
}
看看抛出的异常类系统是如何定义的
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();
final function getTraceAsString();//与getTrace()一样,只不过它将格式化为字符串
function __toString();//需要对象的字符串表示时会自动调用这个方法,也就是一旦有echo或print直接输出Exception实例时就会被调用
}
Exception的属性不能在调用代码中直接访问,而必须使用获取方法获得其属性值,只用$message,$code能有用户抛出异常时设置,即给Exception类的构造函数完成。由Exception类可以看出我们完全可以继承Exception类创建我们自己的异常类,在检测错误时不再抛出系统默认的异常对象,而是我们自定义的异常类对象,但我们只能继承构造函数、toString()方法和Exception的属性。
class myException extends Exception
{
function __toString()
{
return '
}
}
在代码中调用我们自定义的异常类
try
{
throw new myException('错误',10);//为了简单,直接抛出自定义异常对象
}
catch(myException $e)
{
echo $e;//由于我们的自定义异常已经改变了输出方式,所以这里直接输入异常对象即可,原因为一旦有echo或print直接输出Exception实例时就会被调用__toString()
}
以上单间的介绍了异常,下面我们把异常引入我们的数据库处理类中看看如何使用
class myException extends Exception{
function __construct($message=null,$code=0)
{
parent::__construct($message,$code);
}
function __toString()
{
return '
}
}
class mydb {
private $user;//用户名
private $pass;//密码
private $host;//数据库ip地址或localhost
private $db; //数据库名
//构造函数
public function __construct (){
$num_args = func_num_args();
if($num_args > 0){
$args = func_get_args();
$this->host = $args[0];
$this->user = $args[1];
$this->pass = $args[2];
//传入参数后自动调用数据库连接
$this->connect();
}
}
//数据库连接
private function connect (){
//异常处理
try {
if (!$this->db =@ mysql_connect ($this->host,$this->user,$this->pass)){
$exceptionstring = "连接失败:主机、用户名或密码错误 ";
throw new myException ($exceptionstring,0);//抛出自定义异常对象,实例对象时参数错误
}
} catch (myException $e) {
echo $e;
}
}
//数据库选择
public function selectdb ($thedb){
try {
if ([email=!@mysql_select_db]!@mysql_select_db[/email] ($thedb, $this->db)){
$exceptionstring = "数据库: $thedb不存在 ";
throw new myException ($exceptionstring,1);
}
} catch (myException $e) {
echo $e;
}
}
//执行一个update,delete
public function execute ($thequery){
try {
if ([email=!@mysql_query]!@mysql_query[/email] ($thequery, $this->db)){
$exceptionstring = "错误的sql语句: $thequery ";
throw new myException ($exceptionstring,2);
} else {
echo "update/delete受影响: " . mysql_affected_rows () . " 行
";
}
} catch (myException $e) {
echo $e;
}
}
//返回插叙结果
public function getrows ($thequery){
try {
if (!$aquery =@ mysql_query ($thequery)){
$exceptionstring = "错误的查询语句: $thequery ";
throw new myException ($exceptionstring,3);
} else {
while ($adata = mysql_fetch_array ($aquery)){
$returnarr[] =$adata;
}
return $returnarr;
}
} catch (myException $e) {
echo $e;
}
}
//析构函数关闭连接
public function __destruct() {
try {
if ([email=!@mysql_close]!@mysql_close[/email] ($this->db)){
$exceptionstring = "关闭连接失败 ";
throw new myException ($exceptionstring,4);
}
} catch (myException $e) {
echo $e;
}
}
}
//实例类
$mydb = new mydb ("localhost","root","123456");
//选择数据库
$mydb->selectdb ("tonlong");
//执行更新操作
$adata = $mydb->execute ("update db_news set hits=hits+1 where id=3");
//查询输出
$data = $mydb->getrows ("select title from db_news");
for ($i = 0; $i echo $data[$i][0] ."
";
}
?>

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The default map on the iPhone is Maps, Apple's proprietary geolocation provider. Although the map is getting better, it doesn't work well outside the United States. It has nothing to offer compared to Google Maps. In this article, we discuss the feasible steps to use Google Maps to become the default map on your iPhone. How to Make Google Maps the Default Map in iPhone Setting Google Maps as the default map app on your phone is easier than you think. Follow the steps below – Prerequisite steps – You must have Gmail installed on your phone. Step 1 – Open the AppStore. Step 2 – Search for “Gmail”. Step 3 – Click next to Gmail app

Table of Contents Solution 1 Solution 21. Delete the temporary files of Windows update 2. Repair damaged system files 3. View and modify registry entries 4. Turn off the network card IPv6 5. Run the WindowsUpdateTroubleshooter tool to repair 6. Turn off the firewall and other related anti-virus software. 7. Close the WidowsUpdate service. Solution 3 Solution 4 "0x8024401c" error occurs during Windows update on Huawei computers Symptom Problem Cause Solution Still not solved? Recently, the web server needs to be updated due to system vulnerabilities. After logging in to the server, the update prompts error code 0x8024401c. Solution 1

1. First, we right-click the blank space of the taskbar and select the [Task Manager] option, or right-click the start logo, and then select the [Task Manager] option. 2. In the opened Task Manager interface, we click the [Services] tab on the far right. 3. In the opened [Service] tab, click the [Open Service] option below. 4. In the [Services] window that opens, right-click the [InternetConnectionSharing(ICS)] service, and then select the [Properties] option. 5. In the properties window that opens, change [Open with] to [Disabled], click [Apply] and then click [OK]. 6. Click the start logo, then click the shutdown button, select [Restart], and complete the computer restart.

Is the clock app missing from your phone? The date and time will still appear on your iPhone's status bar. However, without the Clock app, you won’t be able to use world clock, stopwatch, alarm clock, and many other features. Therefore, fixing missing clock app should be at the top of your to-do list. These solutions can help you resolve this issue. Fix 1 – Place the Clock App If you mistakenly removed the Clock app from your home screen, you can put the Clock app back in its place. Step 1 – Unlock your iPhone and start swiping to the left until you reach the App Library page. Step 2 – Next, search for “clock” in the search box. Step 3 – When you see “Clock” below in the search results, press and hold it and

Are you getting "Unable to allow access to camera and microphone" when trying to use the app? Typically, you grant camera and microphone permissions to specific people on a need-to-provide basis. However, if you deny permission, the camera and microphone will not work and will display this error message instead. Solving this problem is very basic and you can do it in a minute or two. Fix 1 – Provide Camera, Microphone Permissions You can provide the necessary camera and microphone permissions directly in settings. Step 1 – Go to the Settings tab. Step 2 – Open the Privacy & Security panel. Step 3 – Turn on the “Camera” permission there. Step 4 – Inside, you will find a list of apps that have requested permission for your phone’s camera. Step 5 – Open the “Camera” of the specified app

LinuxOops: Detailed explanation of the meaning of this error, need specific code examples What is LinuxOops? In Linux systems, "Oops" refers to a situation where a serious error in the kernel causes the system to crash. Oops is actually a kernel crash mechanism that stops the system when a fatal error occurs and prints out relevant error information so that developers can diagnose and fix the problem. Oops usually occur in kernel space and have nothing to do with user space applications. When the kernel encounters

Today I would like to introduce to you an article published by MIT last week, using GPT-3.5-turbo to solve the problem of time series anomaly detection, and initially verifying the effectiveness of LLM in time series anomaly detection. There is no finetune in the whole process, and GPT-3.5-turbo is used directly for anomaly detection. The core of this article is how to convert time series into input that can be recognized by GPT-3.5-turbo, and how to design prompts or pipelines to let LLM solve the anomaly detection task. Let me introduce this work to you in detail. Image paper title: Largelanguagemodelscanbezero-shotanomalydete

The abnormality in the pool is a side task in the game. Many players want to know how to complete the abnormality in the pool task. It is actually very simple. First, we must master the technique of shooting in the water before we can accept the task and investigate the source of the stench. Later, we discovered It turns out that there are a lot of corpses under the pool. Let’s take a look at this graphic guide for the unusual tasks in the pool in Rise of Ronin. Guide to unusual missions in the Ronin Rise Pool: 1. Talk to Iizuka and learn the technique of shooting in the water. 2. Go to the location in the picture below to receive the abnormal task in the pool. 3. Go to the mission location and talk to the NPC, and learn that there is a foul smell in the nearby pool. 4. Go to the pool to investigate. 5. Swim to the location in the picture below, dive underwater, and you will find a lot of corpses. 6. Use a camera to take pictures of the corpse. 7
