java抛出异常

参考:https://blog.csdn.net/qq_22067469/article/details/82930798

一般大体分为三种

一.系统抛出异常

public class Abnormal{   
    public static void main(String[] args) {
        int a = 5;
        int b = 0;
        System.out.println( a / b);
    }
}

上述代码抛出ArithmeticException:代码逻辑错。

public class Abnormal{   
    public static void main(String[] args) {
        String str = "abc";
        System.out.println(Integer.parseInt(str));
    }
}

上述代码抛出NumberFormatException:数据类型不对。

2.throw:throw是语句抛出一个异常,一般是在代码的内部,当程序出现某种逻辑错误时同程序主动抛出某种特定类型的异常

public class Abnormal{   
    public static void main(String[] args) {
        String str = "NBA";
        if (str.equals("NBA")) {
            throw new NumberFormatException();
        } else {
            System.out.println(str);
        }
    }

}

3.throws:throws是方法可能会抛出一个异常(用在声明方法时,表示该方法可能要抛出异常)

public static void testThrows() throws NumberFormatException {
    String str = "NBA";
    System.out.println(Integer.parseInt(str));
}

public static void main(String[] args) {
    try {
        testThrows();
    } catch (NumberFormatException e) {
        e.printStackTrace();
        System.out.println("非数直类型不能强制类型转换");
    }
}

捕获异常

捕获异常使用try...catch语句,把可能发生异常的代码放到try {...}中,然后使用catch捕获对应的Exception及其子类:

posted @ 2020-01-06 18:11  lipu1993  阅读(555)  评论(0)    收藏  举报