php,可以将异常抛出2级吗? [英] php, can exceptions be thrown 2 levels up?

查看:110
本文介绍了php,可以将异常抛出2级吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个奇怪的,但在我的代码中,我有开发模式错误和生产模式错误。这是我有的功能:

 私有功能错误($ message,$ mysql_error = null){
if( DEVELOPMENT_MODE){
$ exp = new Exception();
$ trace = $ exp - > getTrace();
array_shift($ trace); //从trace中删除这个函数
$ data [Error Mg] = $ message;
$ data [MySQL Er] =(is_null($ mysql_error))? :$ mysql_error;
array_unshift($ trace,$ data);
fkill($ trace); //格式数组然后死
}
else {
抛出新的异常($ data);
}
}

我在我的数据库类中写了这个函数,如果发生错误,我不需要提供支票,如果我们处于开发模式!



所以我以为我可以外部化可重用的代码。但是,因为我从这个函数抛出异常,我基本上只是使用一个函数,这将返回一个抛出的错误。在生产模式中相当无用。



每次我想使用它,都必须这样做:

  try {
$ this - >错误(连接后无效链接,mysql_error());
} catch(Exception $ exp){
throw $ exp;
}

RATHER THAN JUST

  $ this  - >错误(连接后无效链接,mysql_error()); 

所以为避免写一个try ... catch块为每个错误功能我想调用..有没有办法抛出异常2级?

解决方案

一个例外会自动上线,直到达到最高水平。如果没有被捕获,程序执行将由于未捕获异常而终止。整个例外情况是能够让错误出现。你不需要更加努力或做任何特别的事情来抛出2个等级,这就是它的定义。


I know this is a weird on, but in my code, i have development mode errors, and production mode errors. This is the function i have:

private function error($message, $mysql_error = null){
    if( DEVELOPMENT_MODE ){
        $exp = new Exception();
        $trace = $exp -> getTrace();
        array_shift( $trace ); // removes this functions from trace
        $data["Error Mg"] = $message;
        $data["MySQL Er"] = ( is_null ( $mysql_error ) ) ? "" : $mysql_error;
        array_unshift($trace, $data );
        fkill( $trace );  // formats array and then dies
    }
    else{
        throw new Exception ( $data );
    }
}

I wrote this function in my database class, so that if an error happens, I don't have to provide the check if we're in development mode or not!

So I thought I could externalise the re-usable code. However, because I'm throwing an exception from this function, I'm basically just using a function, that will return a thrown error. Pretty useless in production mode.

I would have to do this every time i want to use it:

try{
    $this -> error( "Invalid Link After Connect.", mysql_error () );
} catch ( Exception $exp ){
    throw $exp;
}

RATHER THAN JUST

$this -> error( "Invalid Link After Connect.", mysql_error () );

so to avoid writing a try ... catch block for every error function I want to call... is there any way to throw the exception 2 levels up?

解决方案

An exception will automatically travel up the call chain until it reaches the highest level. If it's not caught there, program execution terminates due to an uncaught exception. The whole point of exceptions is to be able to have errors bubble up. You don't need to throw harder or do anything special to "throw it up 2 levels", that's what it does by definition.

这篇关于php,可以将异常抛出2级吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆