考虑我有一个包含3个语句的try块,所有这些语句都会导致异常.我希望所有3个例外都由它们相关的catch块处理..是否可能?
像这样的东西 – >
@H_502_8@class multicatch { public static void main(String[] args) { int[] c={1}; String s="this is a false integer"; try { int x=5/args.length; c[10]=12; int y=Integer.parseInt(s); } catch(ArithmeticException ae) { System.out.println("Cannot divide a number by zero."); } catch(ArrayIndexOutOfBoundsException abe) { System.out.println("This array index is not accessible."); } catch(NumberFormatException nfe) { System.out.println("Cannot parse a non-integer string."); } } }
是否有可能获得以下输出? – >>
@H_502_8@Cannot divide a number by zero. This array index is not accessible. Cannot parse a non-integer string.
最佳答案
Is it possible to obtain the following output?
不,因为只会抛出一个异常.一旦抛出异常,执行就会离开try块,并且假设有一个匹配的catch块,它会继续存在.它不会返回到try块,因此您无法获得第二个异常.
有关异常处理的一般课程,请参阅Java tutorial;有关详细信息,请参阅section 11.3 of the JLS.