java学习笔记

异常——java学习之⑨

2018-02-23  本文已影响0人  pm_kai

1,常见异常

2,throws与throw

package ExceptionDemo;
/*
 * 处理异常的两种方式
 * throws抛出异常,try/catch手动捕捉异常
 * throw是手动产生异常
 */
public class ThrowAndThrows {
    public static void main(String[] args) {
        show();
    }
public static void show(){
    int i = 10;
    int b = 2;
    int c = i/b;
    if (b == 2) {
        try {
            throw new Exception();//认为添加异常
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("b不能为2");
        }
    }
}
}

3,手动抛出自定义异常

package ExceptionDemo;

public class CustomDemo {

    public static void main(String[] args) {
        int a=10;
        if (a==10) {
            try {
                throw new Custom1("a不能为10");//手动抛出自定义异常
            } catch (Custom1 e) {
                e.printStackTrace();
            }
        }
    }
}
class Custom1 extends Exception{
    public Custom1(String message) {
        //将信息传递给Exception
        super(message);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读