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("非数直类型不能强制类型转换");
    }
}

猜你喜欢

转载自www.cnblogs.com/lipu12281/p/12157742.html