LoginSignup
6

More than 5 years have passed since last update.

PHPでExceptionを簡潔に書く

Posted at

Exceptionを吐くことのあるメソッドを使う場合は、呼び出し元ですべてtry catchしないといけないと思っていたが、そんなことしなくていいみたい。

綺麗に直したバージョン

実行結果

error

コード

try {
    Hoge::hoge_func();
} catch (Exception $e) {
    print $e->getMessage();
}

class Hoge{
    public static function hoge_func(){
        Fuga::fuga_func();
    }
}

class Fuga{
    public static function fuga_func(){
        throw new Exception("error");
    }
}

冗長に書いてしまっていたバージョン

実行結果は同じですが、無意味にhoge_funcの中でtry catchしてました。

error
try {
    Hoge::hoge_func();
} catch (Exception $e) {
    print $e->getMessage();
}

class Hoge{
    public static function hoge_func(){
        try {
            Fuga::fuga_func();
        } catch (Exception $e) {
            throw $e;
        }
    }
}

class Fuga{
    public static function fuga_func(){
        throw new Exception("error");
    }
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6