Airbrake Blogの「PHPの例外ってそうだったんだ」シリーズが凄いタメになる

ブログもっと雑に書いてこ〜みたいな気持ちがしていた次第。メモとか放り込む

で、タイトルのとおりだけどAirbrakeが「組み込まれている例外、どういうときに使うもの?」というシリーズがありまして。 これが雑学的な読み物としても面白いな〜と思っていつも読んでいる。

今回は PHP Exception Handling – UnexpectedValueException 。 あんま自分は馴染みないかも・・・・と思ったけど。

https://airbrake.io/blog/php-exception-handling/unexpectedvalueexception-2

Not to be confused with the InvalidArgumentException

ほう

For example, if a function is returning a date value, but the runtime execution of this function produces a malformed date, you may opt to throw an UnexpectedValueException

と。前者はわかるぞ(いつもお世話になっております)
しかして、後者だ。すごく名前が似ている感じがする。どう違うの?と思ってみたら、サンプルコードがとても簡潔で良かった

    public function setPublisher(Publisher $publisher) {
        // Confirm that publisher is correct type.
        if (gettype($publisher) == 'object') {
            $class = get_class($publisher);
            if ($class != 'Publisher') {
                // Not a Publisher, so throw a new InvalidArgumentException.
                throw new InvalidArgumentException("Publisher cannot be set to type ({$class}), must be a Publisher object.");
            }
        } else {
            $type = gettype($publisher);
            // Not an object, so cannot be Publisher.
            throw new InvalidArgumentException("Publisher cannot be set to type ({$type}), must be a Publisher object.");
        }
        $this->publisher = $publisher;
    }

InvalidArgument〜は「待って!なにこれ!話が違うだろ!!」って言って投げるもので、UnexpectedValue〜は「あ、やばい!ちょっとうまく約束守れないかも!!」って使う感じかなー