我正在尝试在文件不存在的情况下使用异常处理。例如,当我运行model方法并传递字符串usr(我知道没有使用该名称的文件)时。它给了我以下错误消息
Fatal error: Uncaught exception 'Exception' with message 'Usr.php was not found' in /app/core/controller.php on line 14
我搞不清楚这里出了什么问题。有人能帮我弄清楚吗?
下面是我的代码。非常感谢!
class Controllers{
public function model($model){
if(!file_exists("../app/models/".$model.".php")) {
throw new exception("{$model}.php was not found");
}
try {
require ("../app/models/".$model.".php");
} catch(Exception $e) {
echo $e->getMessage();
}
return new $model();
}
}
您不能在不捕获异常的情况下抛出异常;这会自动导致PHP脚本崩溃。因此,您需要将整个函数包围在try-catch块中,否则将无法捕获"未找到模型"异常。你的代码应该是这样的:
<?php
class Controllers {
public function model($model){
try {
if (!file_exists("../app/models/".$model.".php")) {
throw new Exception("{$model}.php was not found");
}
require ("../app/models/".$model.".php");
} catch(Exception $e) {
echo $e->getMessage();
}
return new $model();
}
}
别介意伙计们!我发现我需要在调用方法的文件中使用try/catch块
示例。。
class Home extends Controllers{
public function index($name = ""){
try{
$user = $this->model('Usr');
}catch (Exception $e){
echo $e->getMessage();
}
//var_dump($user);
}