<?php
class DB{
var $mysql_host="localhost1";//这个是错误的。
var $mysql_user="root";
var $mysql_password="myoa888";
var $my_database="ybjt_oa";
//返回查询结果集
static function getResult($query) {
// 连接
try {
$link = mysql_connect($mysql_host, $mysql_user, $mysql_password);
} catch (Exception $e) {//这里一定错误
return 'Could not connect! ' ;
}
//选择数据库
try {
mysql_select_db($my_database) //这个不出错
} catch (Exception $e) {
return 'Could not select database!';
}
return 'ALL OK!';
}
}
?>
这段程序返回的是 ALL OK请问在 try catch 中的return为什么不会终止程序
你程序里没有产生错误,就没有执行到catch 里去。当然不会返回了。
你把:
var $mysql_host="localhost1";//这个是错误的。
var $mysql_user="root";
var $mysql_password="myoa888";
var $my_database="ybjt_oa";
任意一项设置错了,就会执行到catch 里去了。
try
{
//Do Something A
}
catch()
{
//Do Something B
}//A执行成功了,就没B什么事啦,你把密码改错了,试着运行一次,就知道了
mysql_connect的返回值:
Return Values
Returns a MySQL link identifier on success, or FALSE on failure. try是用来处理一些特殊的异常情况的,比如如果出错会导致系统崩溃,设备占用等。
这里没有必要。
function checkNum($number){
if($number>100){
throw new Exception("This is Exception!!!");
}else{
//This is not Exception.This is false
}
return false;
}try{
//$link = checkNum(100);//try
$link = checkNum(200);
}catch (Exception $e) {//
echo 'Catched!!!!!!!!!!! ' ;
}