Java中异常处理机制有哪些?

如题所述

第1个回答  2018-02-04
1.try和catch语句

●将要处理的代码放入try块中,然后创建相应的catch块的列表。如果生成都异常与catch中提到的相匹配,那么catch条件中的块语句就被执行。try块后可能有许多catch块,每个都处理不同的异常。每个catch中的参数都是Exception的子类。

2.finally语句

●finally语句定义一个总是执行的代码,而不考虑异常是否被捕获。
3.throw引起一个异常

‍●‍‍调用申明抛出异常

public class Test{

static void MethodA() throws ArrayIndexOutOfBoundsException{

int a[] = {1, 2, 3};

for (int i = 0; i < 4; i++) {

System.out.println(a[i]);

}

}

public static void main(String args[]){

try {

MethodA();

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println(e);

}

}

}

●‍throw语句强制抛出异常

public class Test{

public static void main(String args[]){

try {

throw new ArrayIndexOutOfBoundsException();

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println(e);

}

}

}本回答被网友采纳
相似回答