PHP致命错误:不能在没有捕获或最终的情况下使用try

时间:2019-03-05 05:45:41

标签: php

我的网页上出现以下错误致命错误:无法在第13行的apply-for-job.php中尝试使用catch或最后 我自己找不到错误,请帮忙,谢谢。波纹管是我的代码:-

<?php 
    include 'connect.php';
    if(isset($_POST['apply']))
    {
        $fname = $_POST['firstname'];
        $mname = $_POST['middlename'];
        $lname = $_POST['lastname'];
        $city = $_POST['city'];
        $state = $_POST['state'];
        $education = $_POST['education'];
        $vaccancy = $_POST['position'];

        try{

            $stmt = $db_con->prepare('INSERT INTO tbl_employment(firstName,middleName,lastName,userCity,userState,userEducation,userPosition) VALUES (:fname, :mname, :lname, :ucity, :ustate, :uedu, :uvacca)');
            $stmt->bindParam(":fname", $fname);
            $stmt->bindParam(":mname", $mname);
            $stmt->bindParam(":lname", $lname);
            $stmt->bindParam(":ucity", $city);
            $stmt->bindParam(":ustate", $state);
            $stmt->bindParam(":uedu", $education);
            $stmt->bindParam(":uvacca", $vaccancy);
            if ($stmt->execute())
            {
                $message="success";
            }
            else{
                $message="error";
            }
        }
    }

?>

第13行位于 try{ 所在的位置

2 个答案:

答案 0 :(得分:2)

您必须将catchtry一起使用。请查看php.net手册。

  

PHP具有与其他编程语言相似的异常模型。可以在PHP中引发和捕获异常(“捕获”)。可以将代码括在try块中,以帮助捕获潜在的异常。每次尝试都必须至少具有一个相应的捕获或最终阻止。

应该是这样的:

try {
    print "this is our try block n";
    throw new Exception();
} catch (Exception $e) {
    print "something went wrong, caught yah! n";
} finally {
    print "this part is always executed n";
}

您不需要放置finally块,而需要放置catch块。添加catch

时,您的代码可能如下所示
<?php 
include 'connect.php';
if(isset($_POST['apply']))
{
    $fname = $_POST['firstname'];
    $mname = $_POST['middlename'];
    $lname = $_POST['lastname'];
    $city = $_POST['city'];
    $state = $_POST['state'];
    $education = $_POST['education'];
    $vaccancy = $_POST['position'];

    try{

        $stmt = $db_con->prepare('INSERT INTO tbl_employment(firstName,middleName,lastName,userCity,userState,userEducation,userPosition) VALUES (:fname, :mname, :lname, :ucity, :ustate, :uedu, :uvacca)');
        $stmt->bindParam(":fname", $fname);
        $stmt->bindParam(":mname", $mname);
        $stmt->bindParam(":lname", $lname);
        $stmt->bindParam(":ucity", $city);
        $stmt->bindParam(":ustate", $state);
        $stmt->bindParam(":uedu", $education);
        $stmt->bindParam(":uvacca", $vaccancy);
        if ($stmt->execute())
        {
            $message="success";
        }
        else
        {
            $message="error";
        }
    }
    catch(Exception $e)
    {
        // Do the necessary with exception 
    }
}

答案 1 :(得分:0)

您需要捕获尝试抛出的所有异常

try{
    /* your code here */


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