首页 > 解决方案 > javascript 异常与 php7 异常,如何预先知道 throw 语句在 try 块中的位置?

问题描述

考虑以下 javascript 代码调试示例:

try {
  existentFunction1();
  nonExistentFunction();
  existentFunction1();
  existentFunction1();
} catch (error) {
  console.error(error);  // expected output: ReferenceError: nonExistentFunction is not defined  
}

使用的重点try...catch是我不知道里面的哪个函数try会在运行时抛出错误,也就是说,当用户以执行try 语句中的代码的方式与网站交互时,我不想要代码如果其中一项功能无法按预期工作,则停止。

现在如果我想在 php 中做同样的事情,我需要throw声明(至少在 php < 8 中,这篇文章建议我们不需要 throw)。

php代码:

try {
  function1();
  function2();
  // where to put throw? Before or after function3()?
  function3();
  function4();
} 
  catch(Exception $e) {
  echo "Redirect the user to 404 page";
}

我认为解决这个问题的一种方法是使用try...catch每个可疑的功能,这违背了 using 的目的try catch,只使用 a switchorif-else用于所有功能。或者,如果我已经知道哪个函数会产生错误,我根本不需要 try-catch。

我在 php 异常中缺少什么?...来自 javscript 编程背景。

标签: phparraysexceptiontry-catchphp-7

解决方案


推荐阅读