致命错误:无法在第 20 行的 /users/xxx/www/index.php 中使用 try without catch 或 finally

k1o*_*Tho 0 php

这是我第一次使用 PHP,我不知道这段代码有什么问题。

第 20 行是 if 语句: if (isset($_COOKIE['hash'])) {

<?php
if (!isset($_GET['page'])) {
    header('Location: /main');
    exit();
}

ini_set('display_errors','Off');
try {
    $database_host = "localhost";
    $database_name = "NAME";
    $database_user = "USER"; //name for phpMyAdmin in bplaced
    $database_pass = "*******"; //password in phpMyAdmin in bplaced
    global $db;
    $db = mysqli_connect($database_host, $database_user, $database_pass, $database_name) or 
        die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
    mysqli_set_charset($db, "utf8"); 
}

if (isset($_COOKIE['hash'])) {
    $sql = $db->query("SELECT * FROM `users` WHERE `hash` = " . $db->quote($_COOKIE['hash']));
    if ($sql->rowCount() != 0) {
        $row = $sql->fetch();
        $user = $row;
    }
}
Run Code Online (Sandbox Code Playgroud)

Sha*_*yal 6

该错误意味着您的代码缺少一个catch(){}块。

try-catch 的语法是:

try
{
    //Do something here which might cause an exception
}
catch(Exception $e)
{
   //You are here means that the exception occurred now do something else here.
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用 finally 子句,无论是否发生异常都始终执行以下语法:

try
{ 
  print "this is our try block\n";
  throw new Exception();
}
catch (Exception $e)
{
  print "something went wrong\n";
}
finally
{
  print "This part is always executed\n";
}
Run Code Online (Sandbox Code Playgroud)