Simple, Slowly

ブログを引っ越ししました。http://48.jp

例外処理とサンプルコード

例外とは、プログラムの実行中に発生した問題をうまく処理するための仕組みです。
例外を利用すると、プログラムをあまり複雑にすることなくエラー時の対処などを処理できます。
例外が発生する典型的なケースは、整数をゼロで除算した、ファイルが見つからなかった、URLが壊れていた、などの場合です。


サンプルコードをいくつか紹介します。
以下は、0による除算が発生した場合のサンプルコードです。

0による除算が発生した場合の例外処理

<?php
function inverse($x) {
    if (!$x) {
        throw new Exception('ゼロによる除算。');
    }
    else return 1/$x;
}

try {
    echo inverse(5) . "\n";
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo '捕捉した例外: ',  $e->getMessage(), "\n";
}

// 実行は継続される
echo 'Hello World';
?>

様々な例外クラス

例外には様々なクラスが用意されています。
その中から、InvalidArgumentExceptionを紹介します。
引数が期待値に一致しなかった場合にスローされる例外です。
以下のサンプルコードは引数の型をチェックして、int型でなかった場合は例外をスローしています。

<?php
function tripleInteger($int)
{
  if(!is_int($int))
    throw new InvalidArgumentException('tripleInteger function only accepts integers. Input was: '.$int);
  return $int * 3;
}

$x = tripleInteger(4); //$x == 12
$x = tripleInteger(2.5); //exception will be thrown as 2.5 is a float
$x = tripleInteger('foo'); //exception will be thrown as 'foo' is a string
$x = tripleInteger('4'); //exception will throw as '4' is also a string

?>

独自の例外クラス

独自の例外クラスを実装し、それを補足することも可能です。
以下の例は、独自例外クラスのMy1Exceptionを補足するサンプルコードです。
このように、それぞれの例外に対して例外処理を動的に変更することも可能です。

<?php

 My1Exception extends Exception{}
 My2Exception extends Exception{}
 
/**
 * Whereas here, the catch stacking order was changed so our throw will cascade into the correct catch
 */
try {
    throw new My1Exception("My cat's breath smells like cat food", 69);
} catch (My2Exception $e) {
    print "Incorrect Exception";
} catch (My1Exception $e) {
    print "Correct Exception and I WILL be printed";
} catch (Exception $e) {
    print "Again, incorrect";
}

?>


コードはPHPマニュアルからの転載です。