try...catch
함수가 예외를 throw하는 경우에만 의미가 있습니다. 그렇지 않으면 catch
에 아무 것도 없습니다.
이
$results = mysql_query($query);
if (!mysql_num_rows($results)) {
echo 'No results!';
exit;
}
$ids = array();
while (($result = mysql_fetch_row($results)) !== false) {
$ids[] = $result['id'];
}
$ids = array_map('mysql_real_escape_string', $ids);
$query = "DELETE FROM table1 WHERE id IN ('" . join("','", $ids) . "')";
if (!mysql_query($query)) {
echo mysql_error();
exit;
}
$query = "DELETE FROM table2 WHERE id = '$id'";
if (!mysql_query($query)) {
echo mysql_error();
exit;
}
header("Location: list.php?m=4");
exit;
이 여전히 많이 개선 될 수 있지만 이미 스파게티 로직에 비해 개선이다 : 나는 리팩토링으로이 시작 것입니다. 예외를 올바르게 사용하는 데 관심이 있다면 반복 작업 (예 : error, exit
부분)에 대한 함수를 올바르게 사용하고 클래스와 개체로 전체 구조를 다시 구성한 다음 예외를 사용하여 지금 중첩 된 레이어. 어쩌면 PHP 프레임 워크를 사용하여 모든 것을 느낄 수 있습니다.
try {
$results = mysql_query($query);
if (!mysql_num_rows($results)) {
throw new Exception('No results!');
}
$ids = array();
while (($result = mysql_fetch_row($results)) !== false) {
$ids[] = $result['id'];
}
$ids = array_map('mysql_real_escape_string', $ids);
$query = "DELETE FROM table1 WHERE id IN ('" . join("','", $ids) . "')";
if (!mysql_query($query)) {
throw new Exception(mysql_error());
}
$query = "DELETE FROM table2 WHERE id = '$id'";
if (!mysql_query($query)) {
throw new Exception(mysql_error());
}
header("Location: list.php?m=4");
exit;
} catch (Exception $e) {
echo 'ERROR: ' . $e->getMessage();
exit;
}
http://www.w3schools.com/php/php_exception.asp – ArK
당신 유무 : 위의 코드에 예외를 두는
는 설명을 목적으로에 대한
goto
보다 거의 더있을 것이나, 아직 시도한거야? 어떤 부분을 이해하지 못하니? 그리고 네, 오류 처리는 예외의 적절한 사용법입니다. – Matthew