在Java中 try catch是否可以不要catch块
时间:2020-02-23 14:33:58 来源:igfitidea点击:
是的,我们可以使用finally块来实现没有catch块的try语句。
即,可以使用 try finally。
如我们所知,即使在System.exit()的情况下,仍然在try块中具有异常或者返回语句,始终执行。
让我们通过示例来理解
package org.arpit.theitroad; public class TryWithoutCatchMain { public static void main(String args[]) { try { System.out.println("Executing try block"); } finally { System.out.println("Executing finally block"); } } }
执行上面的程序时,我们将获取以下输出:
Executing try block Executing finally block
在try块中有返回语句时会发生什么:
如果在try块中有返回语句,则finally块仍然执行。
package org.arpit.theitroad; public class TryWithoutCatchMain { public static void main(String args[]) { System.out.println(print()); } public static String print() { try { System.out.println("Executing try block"); return "Return from try block"; } finally { System.out.println("Executing finally block"); } } }
执行上面的程序时,我们将获取以下输出:
Executing try block Executing finally block Return from try block
如果我们在finally块中有返回声明,则会发生什么:
它将覆盖了try块返回的任何内容。
让我们通过示例来理解:
package org.arpit.theitroad; public class TryWithoutCatchMain { public static void main(String args[]) { System.out.println(print()); } public static String print() { try { System.out.println("Executing try block"); return "Return from try block"; } finally { System.out.println("Executing finally block"); return "Return from finally block"; } } }
执行上面的程序时,我们将获取以下输出:
Executing try block Executing finally block Return from finally block
如果在try块中抛出异常,那么什么情况:
如果在try块中抛出异常,则finally块仍然执行。
package org.arpit.theitroad; public class TryWithoutCatchMain { public static void main(String args[]) { System.out.println(print()); } public static int print() { try { throw new NullPointerException(); } finally { System.out.println("Executing finally block"); } } }
执行上面的程序时,我们将获取以下输出:
Executing finally block Exception in thread "main" java.lang.NullPointerException at org.arpit.theitroad.TryWithoutCatchMain.print(TryWithoutCatchMain.java:14) at org.arpit.theitroad.TryWithoutCatchMain.main(TryWithoutCatchMain.java:7)