我已经使用try-catch很多年了,但是我从来没有学会如何以及何时使用finally,因为我从来没有理解过finally的意义(我读过不好的书)?
我想问你关于在我的案例中使用finally的问题。
我的代码示例应该可以解释一切:
$s = "";
$c = MyClassForFileHandling::getInstance();
try
{
$s = $c->get_file_content($path);
}
catch FileNotFoundExeption
{
$c->create_file($path, "text for new file");
}
finally
{
$s = $c->get_file_content($path);
}这是finally的正确用法吗?
更精确的问题:
我应该使用finally (在未来的PHP版本或其他语言中)来处理“如果它不存在就创建它”操作吗?
发布于 2013-02-23 03:32:35
Finally将始终被执行,所以在这种情况下,它不是它的预期目的,因为正常执行将再次重新打开文件。如果你这样做了,你打算做的事情也会以同样的(更干净的)方式实现。
$s = "";
$c = MyClassForFileHandling::getInstance();
try
{
$s = $c->get_file_content($path);
}
catch(FileNotFoundExeption $e)
{
$c->create_file($path, "text for new file");
$s = $c->get_file_content($path);
}然后手册上写着:
对于以前没有遇到过
块的人来说,它们与跟随在try/catch块之后的普通代码的关键区别在于,即使try/catch块将控制权返回给调用函数,它们也会被执行。
如果满足以下条件,它可能会执行此操作:
块中抛出另一个异常,并返回try或
最后在这种情况下会很有用:
function my_get_file_content($path)
{
try
{
return $c->get_file_content($path);
}
catch(FileNotFoundExeption $e)
{
$c->create_file($path, "text for new file");
return $c->get_file_content($path);
}
finally
{
$c->close_file_handler();
}
}如果您需要确保在这种情况下关闭文件处理程序或某些资源,则为=>。
发布于 2013-02-23 03:11:59
finally直到5.5版才被引入到PHP中,该版本还没有发布,所以你还没有看到它的任何示例。所以除非你运行的是PHP5.5的alpha版本,否则你还不能使用finally。
手动()中的
在PHP5.5和更高版本中,也可以在catch块之后指定finally块。finally块中的代码将始终在try和catch块之后执行,而不管是否引发了异常,并在正常执行恢复之前执行。
使用finally 手册中的示例
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
else return 1/$x;
}
try {
echo inverse(5) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "First finally.\n";
}
try {
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "Second finally.\n";
}
// Continue execution
echo 'Hello World';
?>发布于 2013-02-23 03:13:27
最终的意思是你最终想做什么。
try
{
$s = $c->get_file_content($path);
}
catch FileNotFoundExeption
{
$c->create_file($path, "text for new file");
}
finally
{
//Create a pdf with my file
//or, Rename my file
//or, store my file into Database
}不管try或catch内部发生了什么(不管是否抛出了异常),'Finally code‘都会执行。所以,没有必要在“try”和“finally”上使用相同的代码。这是否简单地回答了您的问题?
https://stackoverflow.com/questions/15031515
复制相似问题