考虑我有一个包含3个语句的try块,所有这些语句都会导致异常.我希望所有3个例外都由它们相关的catch块处理..是否可能?
像这样的东西 - >
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.");
}
}
}
Run Code Online (Sandbox Code Playgroud)
是否有可能获得以下输出? - >>
Cannot divide a number by zero.
This array index is not accessible.
Cannot parse a non-integer string.
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 10
是否有可能获得以下输出?
不,因为只会抛出一个异常.try一旦抛出异常,执行就会离开块,并且假设存在匹配的catch块,它将继续存在.它不会返回到try块中,因此您无法获得第二个异常.
有关异常处理的一般课程,请参阅Java教程,有关详细信息,请参阅JLS的第11.3节.
| 归档时间: |
|
| 查看次数: |
23238 次 |
| 最近记录: |