1.java Error类与Exception类的区别
Exception:
1.可以是可被控制(checked) 或不可控制的(unchecked)。
2.表示一个由程序员导致的错误。
3.应该在应用程序级被处理。
Error:
1.总是不可控制的(unchecked)。
2.经常用来用于表示系统错误或低层资源的错误。
3.如何可能的话,应该在系统级被捕捉。
2.异常处理的两种方式
异常处理的方式有两种。一种是声明抛出处理:
public class A**Exception {
private String id;
public void setID(String id){
if(id.length() == 7) {
this.id = id;
}
else {
throw new IllegalArgumentException("参数长度不是7位");
}
}
}
另外一种是捕获处理:
public class TestCatchError extends Error{
private static final long serialVersionUID = -351488225420878020L;
public TestCatchError(){
super();
}
public TestCatchError(String msg){
super(msg);
}
public static void main(String[] args) {
try {
throw new TestCatchError("test catch error");
} catch (Throwable t) {
System.out.println("step in the catch ~");
t.printStackTrace();
}
}
}
3.RuntimeException类的五个子类
1, ClassCastException类转换异常
Object x = new Integer(0);
System.out.println((String)x); 当试图将对象强制转换为不是实例的子类时,抛出该异常
2,ArithmeticException算术异常
int a=5/0; 一个整数“除以零”时,抛出异常
3, NullPointerException空指针异常
String s=null; int size=s.size();
当应用程序试图在需要对象的地方使用 null 时,抛出异常
4,IllegalArgumentException参数异常
抛出的异常表明向方法传递了一个不合法或不正确的参数
5,ArrayIndexOutOfBoundsException数组下标越界异常
当使用的数组下标超出数组允许范围时,抛出该异常