2016-05-31 1 views
-1

私は、読みにくくなっているIF/THENロジックがあります。代わりに例外を使用することを考えています。異なるPHP例外を区別する

コードはユーザー入力をテストし、必要に応じて例外をスローします。私のキャッチステートメントは予期される例外を処理しますが、例外が予期されない場合(PDOステートメントを乱したような)、例外をスローしてPHPのエラーシステムに処理させたいと思います。予想される例外はすべて同じように処理されているため、テストごとに複数のtry/catchを使用することは望ましくありません。

catchステートメント内で、例外に基づいてどのように異なるアクションを実行できますか?

try { 
    $user_input=$_POST['user_input']; 
    // rest of code here... 
    if (test1($user_input)) { 
     throw new Exception("Anticipated exception 1."); 
    } 
    // rest of code here... 
    //Some PDO which might generate a non-anticipated exception 
    if (test2($user_input)) { 
     throw new Exception("Anticipated exception 2."); 
    } 
    // rest of code here... 
} 
catch (Exception $e) { 
    if(anticipatedException($e)) { 
     //Deal with it 
    } 
    else { 
     throw $e; 
    } 
} 
+0

はあなたのグループあなたの特定の例外が共通の祖先を持つことができませんでした:

class ExceptionOne extends Exception {} class ExceptionTwo extends Exception {} try { $user_input=$_POST['user_input']; // rest of code here... if (test1($user_input)) { throw new ExceptionOne("Anticipated exception 1."); } // rest of code here... //Some PDO which might generate a non-anticipated exception if (test2($user_input)) { throw new ExceptionTwo("Anticipated exception 2."); } // rest of code here... } catch (ExceptionOne $e) { /*...*/ } catch (ExceptionTwo $e) { /*...*/ } 

はまた、グループあなたに役立つかもしれない定義済みの例外をチェックする、すなわち? – mario

+0

@marioわかりません。詳しく教えてください。 – user1032531

+2

'UserInputTooShortExcはCommonInputExceptions'と' UserInputTooLong'などを同じように拡張します。代わりに 'Common..Exc'をキャッチするだけです。 – mario

答えて

2

異なる例外を使用します。 http://php.net/manual/en/spl.exceptions.php

+0

ありがとう、ジョハンズ。 PDO例外はどこで捕捉されますか?私は 'catch(Exception $ e){throw $ e;}'を最後に置くことができますか? – user1032531

+0

PDOが 'PDOException'をスローするので、' catch(PDOException $ e) 'http://php.net/pdoexception – johannes

+0

ああ、気にしないでください。思っていませんでした。 PDO例外が発生した場合、それは捕捉されないので、なぜそれを捕まえて再度投げますか?ありがとう、それを得た! – user1032531

関連する問題