Skip to content

Instantly share code, notes, and snippets.

@fumikito
Created January 19, 2014 04:33
Show Gist options
  • Select an option

  • Save fumikito/8500514 to your computer and use it in GitHub Desktop.

Select an option

Save fumikito/8500514 to your computer and use it in GitHub Desktop.
catchブロックの中でエラーを投げてみる
<?php
/**
* catchブロックの中でエラーを投げてみる
*
* php try-catch.php 1000と入力すると、
* Uncaught exceptionが発生。したがって、こういうことをやりたい場合は
* 入れ子にしないとダメ。
* 結果的に、例外の種類が増えると入れ子がどんどん深くなっていく
* 5.5ならfinally があるので、もうちょっとすっきりできる
*/
// 以下、OK
try{
try{
if(!isset($argv[1])){
throw new Exception('パラメータなし');
}elseif( !is_numeric($argv[1]) ){
throw new Exception('数字じゃないとダメです');
}elseif( $argv[1] > 100 ){
throw new ErrorException('100より小さくないとダメです');
}else{
printf('%dが入力されました'.PHP_EOL, $argv[1]);
}
}catch (ErrorException $e){
throw new Exception('ErrorExeption発生: '.$e->getMessage());
}
}catch (Exception $e){
echo $e->getMessage().PHP_EOL;
}
// 以下、NG
try{
if(!isset($argv[1])){
throw new Exception('パラメータなし');
}elseif( !is_numeric($argv[1]) ){
throw new Exception('数字じゃないとダメです');
}elseif( $argv[1] > 100 ){
throw new ErrorException('100より小さくないとダメです');
}else{
printf('%dが入力されました'.PHP_EOL, $argv[1]);
}
}catch (ErrorException $e){
throw new Exception('ErrorExeption発生: '.$e->getMessage());
}catch (Exception $e){
echo $e->getMessage().PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment