可以为PHP中的所有函数放置一个Try Catch块[关闭]

可以为PHP中的所有函数放置一个Try Catch块[关闭]

问题描述:

How Can I put one Try catch block for one complete class.

PS: I know that I can separate put try catch in each function but just asking if there is a way to put on try catch above a class.

如何为一个完整的类放置一个Try catch块。 p>

PS:我知道我可以在每个函数中将try try分开,但只是询问是否有办法在类上面设置try catch。 p> div>

Based on your clarification from the comment, it seems you don't need no try or catch. But exception handler instead.

Just have your 400+ methods have to throw 400+ exceptions - they all will be processed in one handler.

P.S. It seems most of SO folks cannot tell a negative answer from negative vote

No, you can't do that. The reason to use try catch is to catch specific exceptions wich may be different for each function in a class.

Wrong:

class Test
{
    try {
        public function foo(){
            return 'foo';
        }

        public function bar(){
            return 'bar';
        }
    catch (\Exception $e) {
        echo $e->getMessage();
    }
}

Correct:

class Test
{
    function foo(){
        try {
            return 'foo';
        catch (\Excepetion $e) {
            return $e->getMessage();
        }
    }

    function bar(){
        try {
            return 'bar';
        catch (\Excepetion $e) {
            return $e->getMessage();
        }
    }
}