1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHP try{}catch, throw, Exceptionの考え方(基本)

Posted at

#例外処理についての基本

例)


function d($x,$y){
    if($y ==0){
        throw new Exception('0では割れない');
    }
    return $x/$y;
}

try{
    echo d(8,3)."\n";
    echo d(5,0)."\n";
    echo d(4,2)."\n";
}catch(Exception $e){
    echo $e->getMessage();
}

結果
/*
2.6666666666667
0では割れない
*/

上記の通りecho d(4,2)の処理は2番目のecho d(5,0)にて第二引数に0があり関数内の例外処理に引っ掛かる為
throwで定義される例外処理が働きtry文の処理がcatch(){}へ移動する。

個人的に最初echo(4,2)の処理も行われると思っていたが、どうやら違う様子。
この部分を覚える為の備忘録。

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?