dtiu94034 2013-06-12 19:06 采纳率: 0%
浏览 401
已采纳

只有在没有抛出异常的情况下,才能在try块之外执行代码的最简洁方法

This question is about the best way to execute code outside of try block only if no exception is thrown.

try {
    //experiment
    //can't put code after experiment because I don't want a possible exception from this code to be caught by the following catch. It needs to bubble.
} catch(Exception $explosion) {
    //contain the blast
} finally {
    //cleanup
    //this is not the answer since it executes even if an exception occured
    //finally will be available in php 5.5
} else {
    //code to be executed only if no exception was thrown
    //but no try ... else block exists in php
}

This is method suggested by @webbiedave in response to the question php try .. else. I find it unsatisfactory because of the use of the extra $caught variable.

$caught = false;

try {
    // something
} catch (Exception $e) {
    $caught = true;
}

if (!$caught) {

}

So what is a better (or the best) way to accomplish this without the need for an extra variable?

  • 写回答

2条回答 默认 最新

  • duanmu2941 2013-06-12 19:23
    关注

    One possibility is to put the try block in a method, and return false if an exception is cought.

    function myFunction() {
        try {
            // Code  that throws an exception
        } catch(Exception $e) {
            return false;
        }
        return true;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应