【发布时间】:2013-04-19 14:27:26
【问题描述】:
我已经在 PHP 和 C++ 中尝试过,所以我的问题只针对它们。为什么我们必须自己throw异常并且在出现异常问题时它们不会自动抛出。
PHP 代码优先
<?php
try{
$a=1;
$b=0;
echo $a/$b;
} catch (Exception $e) {
echo "Error : ".$e->getMessage();
}
?>
为什么这段代码不会抛出除以零异常?可以通过以下方式完成
<?php
try{
$a=1;
$b=0;
if($b==0)
{
throw new Exception("What's the point in an exception if its not automatic and i have to throw it myself");
}
echo $a/$b;
} catch (Exception $e) {
echo "Error : ".$e->getMessage();
}
?>
但是异常处理的意义何在,如果我必须自己编写可能的异常代码,那么为什么不使用任何简单的错误报告模式呢?
以下同样适用
C++ 代码
int main()
{
try{
int a=1;
int b=0;
cout<<(a/b);
}
catch (string e)
{
cout << e << endl;
}
}
如果没有进行异常处理,这不会产生异常,会产生运行时错误并使应用程序崩溃。以下作品
int main()
{
try{
int a=1;
int b=0;
if(b==0)
{
throw string("What's the point in an exception if its not automatic and i have to throw it myself");
}
cout<<(a/b);
}
catch (string e)
{
cout << e << endl;
}
}
问题
为什么我必须手动检查这些变量才能发现错误?当我已经告诉代码这会发生时,异常真的是异常吗?那为什么优先于基本if条件
【问题讨论】:
-
这真的是您在 PHP 中唯一需要抱怨的事情吗? me.veekun.com/blog/2012/04/09/php-a-fractal-of-bad-design
-
除以零不会产生异常,它会产生错误。
-
感谢 nickb 的说明。感谢 SLaks 提供的信息链接 :)
标签: php c++ exception divide-by-zero