使用级联捕获异常
try{
…...
}catch(ArrayIndexOutOfBoundsException e) {
……
} catch(ArithmeticException e) {
……
} catch(Exception e) {
……
}
注意:使用多重 catch 语句时,异常子类一定要位于异常父类之前。
所以以下这种方式是错误的。
try{
…...
} catch(Exception e) {
……
} catch(ArrayIndexOutOfBoundsException e) {
……
}
好,那么我们可以修改上面的代码如下:
public class Cal { public int div(int a, int b) { int result = a / b; return result; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int s = 0; int num1 = 0; int num2 = 0; try { //1、这里可能会抛出异常 System.out.print("num1="); num1 = scanner.nextInt(); System.out.print("num2="); num2 = scanner.nextInt(); Cal cal = new Cal(); //2、这里也可能抛出异常 s = cal.div(num1, num2); } catch (ArithmeticException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (InputMismatchException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } System.out.println(s); } }
由于多次的使用try或影响效率。所以我们如果碰到循环的时候,应该把try语句放到循环的外面,例如我们并不推荐你这样写代码:
public static void main(String[] args) { int[] arr = { 1, 2, 3, 4 }; Cal cal = new Cal(); for (int i = 0; i < arr.length; i++) { try { int s = cal.div(arr[i], 2); } catch (Exception e) { // TODO: handle exception } } }
你可以修改成为这样:
public static void main(String[] args) { int[] arr = { 1, 2, 3, 4 }; Cal cal = new Cal(); try { for (int i = 0; i < arr.length; i++) { int s = cal.div(arr[i], 2); } } catch (Exception e) { // TODO: handle exception } }