检测异常 - 如果

时间:2011-12-14 03:47:33

标签: php exception

如果我有这个:

function valid($valor) {
        foreach($valor as $valor){
            if (!empty($valor)) {
                if (preg_match("/[^A-Za-z0-9-áàçéúâôóã ]|(\d+)/", $valor)) {
                    $error = "invalid";
                    throw new Exception($error);
                }
            }
        }
    }

if (isset($_POST['myform'])){
    if ($val_->valid($form1['new'])) {
        echo "ok";
    }
    else 
        echo "bad";
}

但我得到了:Fatal error: Uncaught exception 'Exception

我想要的基本上是那样的(伪代码):

if (exception true) {
    echo "problem";
}
else
    echo "ok";

我该怎么做?

1 个答案:

答案 0 :(得分:4)

您必须处理exception

try {
    ...
    //statements
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

编辑:

 try{
   if ($val_->valid($form1['new'])) {
     echo "ok";
    }
  }catch(Exception $e){   
     echo "bad";
   }