异常处理
写健壮应用时经常会提到的异常处理,一般遵循着80/20原则: 80%的代码用于处理异常或者验证,20%的代码没什么实际的用途。原始的代码通常都是在乐观的环境下编写的。这意味着代码可以在数据正常、一切理解的基础环境中工作的很好。但是这种代码在其生命周期内是脆弱的。在极端的情形中,你得花更多的时间来未很可能永远不会发生的状况编写相应代码。
这个习惯就是要你处理全部的出错情况,而且如果要是不这么做,你的代码永远也完不成。
坏习惯:不处理任何异常
<?php
// Get the actual name of the function convertDayOfWeekToName($day) { $dayNames = array( "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"); return $dayNames[$day]; }
echo("The name of the 0 day is: " . convertDayOfWeekToName(0) . "\n"); echo("The name of the 10 day is: " . convertDayOfWeekToName(10) . "\n"); echo("The name of the ''orange'' day is: " . convertDayOfWeekToName(''orange'') . "\n");
?>
|
好习惯: 防守型编程
例8表明处理并抛出异常是一件很有意义的事情。不只是额外的异常处理可以让代码健壮,但是这有助于提高代码的可读性。这种异常处理为原作者查看何时编写提供了一个很好的说明。
例8.好习惯:防守型编程
<?php
/** * This is the exception thrown if the day of the week is invalid. * @author nagood * */ class InvalidDayOfWeekException extends Exception { }
class InvalidDayFormatException extends Exception { }
/** * Gets the name of the day given the day in the week. Will * return an error if the value supplied is out of range. * * @param $day * @return unknown_type */ function convertDayOfWeekToName($day) { if (! is_numeric($day)) { throw new InvalidDayFormatException(''The value \'''' . $day . ''\'' is an '' . ''invalid format for a day of week.''); }
if (($day > 6) || ($day < 0)) { throw new InvalidDayOfWeekException(''The day number \'''' . $day . ''\'' is an '' . ''invalid day of the week. Expecting 0-6.''); }
$dayNames = array( "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"); return $dayNames[$day]; }
echo("The name of the 0 day is: " . convertDayOfWeekToName(0) . "\n");
try { echo("The name of the 10 day is: " . convertDayOfWeekToName(10) . "\n"); } catch (InvalidDayOfWeekException $e) { echo ("Encountered error while trying to convert value: " . $e->getMessage() . "\n"); }
try { echo("The name of the ''orange'' day is: " . convertDayOfWeekToName(''orange'') . "\n"); } catch (InvalidDayFormatException $e) { echo ("Encountered error while trying to convert value: " . $e->getMessage() . "\n"); }
?>
|
|