2020-10-27

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数组下标越界异常
当使用的数组下标超出数组允许范围时,抛出该异常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值