dongqindan4406 2019-02-16 08:20
浏览 25
已采纳

错误处理可能无法在PHP脚本中工作

I have a PHP script that goes like:-

<?php session_start() ?>

<body>
 <?php 
   try{
      $userId=$_GET['userId'];
   }
   catch(Exception $e){
      $userId=$_SESSION['userId2'];
   }?>

with $userId=$_GET['userId']; this being my line number 23.

I'm loading the script using http://localhost/checkIdAbout.php?all=ALL.

Now clearly my URL doesn't have the value for $userId, so it'll give an error and that's understandable to me. What I don't understand is that why isn't the try-catch block coming into play? I already stored the value for $_SESSION['userId2']. So shouldn't during execution the code jump from try to catch and give me the required value for $userId?

I get the error: Notice: Undefined index: userId in /var/www/html/checkIdAbout.php on line 23 and I just can't get what's wrong. Please help. Thanks!

  • 写回答

1条回答 默认 最新

  • dronthpi05943 2019-02-16 10:53
    关注

    A notice is not an exception.

    You could write a custom handler to convert notices to exceptions:

    set_error_handler(function ($errno , $errstr, $errfile, $errline) {
        if (!(error_reporting() & $errno)) {
            return false;
        }
        throw new ErrorException($errstr, $errno, $errno, $errfile, $errline);
    }, E_NOTICE);
    
    try {
        $foo++;
    } catch (ErrorException $e) {
        echo 'Notice cast to exception: '. $e->getMessage(), PHP_EOL;
    }
    

    ... but it's normally a bad idea because throwing an exception interrupts the script flow until next catch (or totally aborts the script if none). And, in this case, I don't think it's justified to intentionally cause a notice just to be able to use exception handling, when there're simpler alternatives, e.g.:

    $userId = filter_input(INPUT_GET, 'userId') ?? $_SESSION['userId2'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?