1
2

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

Posted at

phpで例外処理というものがあることを知った。

書き方:

try {
    // ロジック(処理)を記載

    //例外が発生したら例外を投げる
    throw new Exception();

} catch(Exception ex) {
    // 例外が渡ってくるところ
}

try{
   echo 111;
   throw new Exception();
}catch(Exception e){
   echo '捕捉した例外: ' . $e->getMessage()
}

こんな感じ。

いつ使うかというと、例外処理が行われるとき!!!!
わかりやすくいうと、
予期しないエラーや予期しない動作をした際に処理を中断して
catch()に処理が流れる。
かな。

try()の中での処理は普通は正常に動いてほしい。
しかし、途中でpcが落ちたりいろんな例外なことが起きた際に
try()の中の処理を無かったことに巻き戻しcatch()へ処理を流すもの。

例外がcatchされたら、try()を宣言する前まで処理が巻き戻される。

銀行のATMの例がわかりやすかったかな。
口座から100円引出したと思ったら、途中でATMが故障。
口座からは100円引かれているのに、手元には100円はない。

こういったことが起こらないように、try()の中は塊の1処理として扱い
エラーが起きたらcatch()へ処理が流れる。

その際に、getMessage()を使用するとほとんどの場合エラー内容が吐かれる。

try(){

  //100円を口座からマイナスする処理
  //     <-----ここでエラーが発生
  //100円をATMから出す処理

}catch(Exception e){
  echo $e->getMessage();
  //ここに飛んできたら、100円を口座からマイナスする処理は行われ無かったことになる
そして、エラーの原因が表示される。
}

参考:https://hara-chan.com/it/programming/php-try-catch/

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?