V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
guyeuro
V2EX  ›  问与答

Java : try catch 包围的代码多一点好还是少一点好?

  •  
  •   guyeuro · 2017-08-28 18:30:14 +08:00 · 2293 次点击
    这是一个创建于 2441 天前的主题,其中的信息可能已经有所发展或是发生改变。

    譬如

    FileInputStream in;
    try{
       in = new FileInputStream(fileName);
    }catch(e){
        ...
    }
    
    if(in !=null){
       ...
       in.read();
    }
    
    ...
    
    if(in !=null){
       ...
       in.write();
    }
    

    还是

    try{
       in = new FileInputStream(fileName);
       
       。。。
       。。。
       in.read();
       ...
       ...
       in.write();
    }catch(e){
        ...
    }
    

    BTW:

    如果有多处可能抛出异常,是用一个 try-catch,集中处理,还是每个异常可能点都用一个 try-catch 好?

    7 条回复    2017-08-28 19:35:39 +08:00
    xCris
        1
    xCris  
       2017-08-28 18:31:01 +08:00
    为啥是王者荣耀?
    verrickt
        2
    verrickt  
       2017-08-28 18:39:23 +08:00 via Android
    道理我都懂,为啥不用 try with resources?
    当年学 java 的时候被文件 IO 那块嵌套的 try catch 恶心的不行
    kaneg
        3
    kaneg  
       2017-08-28 18:51:56 +08:00 via iPhone
    try 次数越少越好。

    能用一个就不要用多个
    kokutou
        4
    kokutou  
       2017-08-28 19:00:23 +08:00
    当年初学直接 mian 函数接着一个 try-catch,所有函数都 throw 2333

    当然现在就是 try with resources 了:
    https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
    movistar
        5
    movistar  
       2017-08-28 19:08:30 +08:00   ❤️ 1
    取决于需不需要 FAIL FAST
    如果你前面的流程挂了,后面的流程还能执行,那就多个 try catch 分开
    如果前面挂了整个流程就挂了,那就写一个 try catch.....
    这个和 try with resources 没啥关系
    ihuotui
        6
    ihuotui  
       2017-08-28 19:35:09 +08:00 via iPhone
    看有没有必要,不是多与少。还有就是封装异常,保持整洁,即使函数增加功能,也不怕调用函数改变。
    其实还是要多看书多思考。
    ihuotui
        7
    ihuotui  
       2017-08-28 19:35:39 +08:00 via iPhone
    @ihuotui 整洁代码之道,单元测试 junit,重构。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1184 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 17:40 · PVG 01:40 · LAX 10:40 · JFK 13:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.