我们可以在 Java 中定义一个带有多个 catch 块的 try 块吗?
javaobject oriented programmingprogramming
是的,我们可以在 Java 中定义一个带有多个 catch 块的 try 块。
- 每个 try 都应该且必须与至少一个 catch 块相关联。
- 每当在 try 块中识别出异常对象时,如果有多个 catch 块,则将根据定义 catch 块的顺序确定 catch 块的优先级。
- 始终将最高优先级赋予第一个 catch 块。如果第一个 catch 块无法处理识别出的异常对象,则它会考虑紧接着的下一个 catch 块。
示例
class TryWithMultipleCatch { public static void main(String args[]) { try{ int a[]=new int[5]; a[3]=10/0; System.out.println("First print statement in try block"); } catch(ArithmeticException e) { System.out.println("Warning: ArithmeticException"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Warning: ArrayIndexOutOfBoundsException"); } catch(Exception e) { System.out.println("Warning: Some Other exception"); } System.out.println("Out of try-catch block"); } }
输出
Warning: ArithmeticException Out of try-catch block