问题
I am working on table that prints addresses from a MySQL database. I'm not sure I understand try/catch blocks very well. Old records have no IP address but new records do have an IP address in the table. The new records (with an IP address) print out fine, but only if I put it in a try catch like below:
try {
echo inet_ntop($row['ip']);
}
catch (Exception $e){
//echo 'Exception caught: ', $e->getMessage(), "\n";
echo "n/a";
}
The records that don't have an IP in the IP field print out an ugly error. As show above, I commented out the error, but it prints an error anyway. How can I properly print a table full of the present IP addresses (or lack 0f) without having to look at all of these errors:
Warning: inet_ntop() [function.inet-ntop]: Invalid in_addr value in/home/zp/public_html/example.COM/example.php on line 57
回答1:
Warnings
are not catch
able. try..catch
blocks work on Exceptions only. Warnings are a different error reporting mechanism entirely. To suppress warnings, you can use the error control operator:
$ip = @inet_ntop($row['ip']);
echo $ip ? $ip : 'n/a';
Of course, you should avoid warnings altogether by validating the values you pass into inet_ntop
first. At the very least:
echo $row['ip'] ? inet_ntop($row['ip']) : 'n/a;
回答2:
inet_ntop
does not throw an exception you can catch, for example:
try
{
test_function();
}
catch(Exception $e)
{
//Relax
}
function test_function()
{
throw new Exception("Something went wrong");
}
Will catch as expected, what you should be doing is preventing errors by doing sufficient checking:
try
{
$is_valid = filter_var($row['ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) || filter_var($row['ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
if(!$is_valid)
{
throw new Exception('Invalid IP Address');
}
echo inet_ntop($row['ip']);
}
catch(Exception $e)
{
echo 'n/A';
}
回答3:
You can suppress the warning like this, though RobertPitt's answer is far better:
echo(@inet_ntop($row['ip']));
来源:https://stackoverflow.com/questions/6577327/try-inet-ntoprowip-catchgracefully-in-php