76 try-catch-finally 中哪个部分可以省略?

try-catch-finally 中哪个部分可以省略?

答:

以下三种情况都是可以的:
try-catch
try-finally
try-catch-finally
可以省略catch或者finally。catch和finally不可以同时省略。
 

原文链接: https://www.baidu.com/link?url=QXjO_NMZxfr81-tF63dpGL7k2BQ2BUl-2LvNwyXB3fMLxLfaDcXe3bizfwRaFYRA4vO0tb-612BlCHwFodL7UK&wd=&eqid=827581c70029024f000000035ed98790
 


package constxiong.interview;
 
public class TestOmitTryCatchFinally {
 
    public static void main(String[] args) {
        omitFinally();
        omitCatch();
    }
    
    /**
     * 省略finally 语句块
     */
    public static void omitFinally() {
        try {
            int i = 0;
            i += 1;
            System.out.println(i);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 省略 catch 语句块
     */
    public static void omitCatch() {
        int i = 0;
        try {
            i += 1;
        } finally {
            i = 10;
        }
        System.out.println(i);
    }
}

 

你可能感兴趣的:(76 try-catch-finally 中哪个部分可以省略?)