在catch异常的情况下读取数组

时间:2013-08-27 11:49:12

标签: php arrays try-catch

在catch(Exception $ e)的情况下,以下代码在$ lat = $ track [0]行失败。如何解决?

$track = getPositionalTrack();
$lat = $track[0];
$lon = $track[1];

function getPositionalTrack()
{
    $track = array();
    $url = "https://...";
    try
    {
        $result = file_get_contents($url);
        $obj = json_decode($result, true);
        $lat =  $obj["lat"];
        $lon = $obj["lon"];
        $track[0] = $lat;
        $track[1] = $lon;
    }
    catch (Exception $e)
    {
        die('ERROR: ' . $e->getMessage());
    }
    return $track;
}

2 个答案:

答案 0 :(得分:2)

与deceze一样,file_get_contentsjson_decode都不会引发异常。 因此,您必须以防御方式重写该函数以捕获错误。

function getPositionalTrack()
{
    $url = "https://...";

    $result = file_get_contents($url);
    if (false === $result) {
        return null;
    }

    $obj = json_decode($result, true);
    if (null === $obj) {
        return null;
    }

    if (isset($obj['lat']) && isset($obj['lon'])) {
        return $obj;
    }

    return null;
}

$track = getPositionalTrack();
if (null !== $track) {
    $lat = $track['lat'];
    $lon = $track['lon'];
}

或者在函数中抛出异常:

function getPositionalTrack()
{
    $url = "https://...";

    $result = file_get_contents($url);
    if (false === $result) {
        throw new Exception('file_get_contents failed');
    }

    $obj = json_decode($result, true);
    if (null === $obj) {
        throw new Exception('json_decode failed');
    }

    if (isset($obj['lat']) && isset($obj['lon'])) {
        return $obj;
    }
    else {
        throw new Exception('no lat/lon keys');
    }

}

try {
    $track = getPositionalTrack();
    $lat = $track['lat'];
    $lon = $track['lon'];
}
catch (Exception $e) {
    // react on failure
}

答案 1 :(得分:0)

顺便说一下它失败了,track是一个空数组,所以$ track [0]会像你说的那样“失败”。

您可以尝试这样的事情:

catch (Exception $e)
{
    $track[0] = //something
    $track[1] = //something else
}

或者在你的函数调用之后处理它,但它会很混乱