在Java中,每个try块后面都必须紧跟catch块吗?
问题是“在Java中,每个try块后面都必须紧跟catch块吗?”
答案是“不,在Java中,每个try块后面都没有catch块不是强制性的。”
在try块之后,我们可以使用“catch”块或“finally”块。
通常,应在方法的thrown子句中声明抛出的异常。
为了理解try-catch块,我们将讨论三种情况:
如果每个try块后面都必须有catch块,将会发生什么情况?
如果每个try块后面都必须有一个finally块,将会发生什么情况?
如果每个try块后面都必须同时包含catch和finally块,将会发生什么情况?
在接下来的几个步骤中,我们将借助一个示例逐一探讨上述每种情况,
1)每个try块后面都有一个catch块
示例
//Java程序演示的例子 //try-catch块层次结构 public class TryCatchBlock { public static void main(String[] args) { try { int i1 = 10; int i2 = 0; int result = i1 / i2; System.out.println("The divison of i1,i2 is" + result); } catch (Exception ex) { ex.printStackTrace(); } } }
输出结果
java.lang.ArithmeticException: / by zero at TryCatchBlock.main(TryCatchBlock.java:8)
2)每个try块后面都有一个finally块
示例
//Java程序演示的例子 //最后尝试块层次结构 public class TryFinallyBlock { public static void main(String[] args) { try { int i1 = 10; int i2 = 0; int result = i1 / i2; System.out.println("The divison of i1,i2 is" + result); } finally { System.out.print("Code which must be executed :" + " "); System.out.println("Whether Exception throw or not throw"); } } }
输出结果
Code which must be executed : Whether Exception throw or not throw Exception in thread "main" java.lang.ArithmeticException: / by zero at TryFinallyBlock.main(TryFinallyBlock.java:11)
3)每个try块后面都有catch和finally块
示例
//Java程序演示的例子 //try-catch-finally块层次结构 public class TryCatchFinallyBlock { public static void main(String[] args) { int i1 = 10; int i2 = 0; try { int result = i1 / i2; System.out.println("The divison of i1,i2 is" + result); } catch (Exception ex) { int result = i1 + i2; System.out.println("The addition of i1,i2 is" + " " + result); } finally { System.out.print("Code which must be executed :" + " "); System.out.println("Whether Exception throw or not throw"); } } }
输出结果
The addition of i1,i2 is 10 Code which must be executed : Whether Exception throw or not throw
下面给出的try,catch和finally的组合是有效的,并且我们已经借助上面给出的示例进行了查看,
尝试捕获块
try-catch-finally块
最后尝试块