18
22

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 5 years have passed since last update.

例外処理について解説!

Last updated at Posted at 2019-05-05

例外処理とは

  • 意図しないエラー(例外)が発生したときに備えて、自分なりの処理を設定したり、メッセージを表示させたりと何かしらの対策をしておくことです。

エラー(例外)が発生する事例

  • 読み込むファイルが存在しない
  • データベースの処理においてSQL文の構文エラー
  • 0で割り算をした など

例外処理の書き方

<?php

try {

//例外が発生する可能性があるコード

throw new 例外クラス名(引数)

}catch(例外クラス名 例外を代入する変数名){

//例外が発生した場合に行う処理

}

//エラーが発生しなければ続く通常の処理

解説

上記について解説します。

「throw new 例外クラス名(引数)」とは

  • 例外が発生することを例外を投げる(スローする)といいます。
  • throw new 例外クラス名(引数)でインスタンスを作成しています。

「例外クラス名」とは

  • phpには最初から定義済みの例外クラスがいくつかあります。
  • (例)「Exceptionクラス」
  • ここでは、その例外クラス名を定義します。

「例外を代入する変数名」とは

  • 例外処理ではcatchしたときにインスタンスを変数に代入します。
  • throw new 例外クラス名(引数)でインスタンスを作成して、catch(例外クラス名 例外を代入する変数名)でインスタンスを変数に代入しています。

コード例

<?php

function division($int1,$int2) {
    try {
        if($int2 == 0) {
      
            throw new Exception('0で割れません');
        }
        return $int1 / $int2;


    } catch(Exception $e) {

        echo "例外処理が発生しました";
        echo "<br>";
        echo $e->getMessage();

    }
}

echo division(10,0);

実行結果
例外処理が発生しました
0で割れません

解説

  • 例外が発生する可能性がある箇所をtry{}に書きます。
  • throw new Exception()で例外を投げます。
  • 例外が投げられた時の処理をcatch(){}に書いていきます。

getMessage()メソッドとは

  • 例外メッセージを取得するインスタンスメソッドです。
  • 例外メッセージは、インスタンスを作成するときに第一引数に指定した文字です。
  • 上記の場合、0で割れませんが例外のメッセージです。
18
22
3

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
18
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?