异常抛出throw与throws

一.throw(语句抛出异常)

throw <异常对象>

throw new Exception();

此语句将抛出异常 

二.throws(方法抛出异常)

<修饰符><返回类型><方法名><参数列表>throws 异常类{}

public static void div(int b)throws Exception{}

 此方法将抛出异常 

三.

throws可单独使用

throw不可单独使用

1.若方法用throws则方法中可直接使用throw

2.若方法没用throws则throw要使用try{}catch{}语句

public static void div(int b){
        if(b==0) {
            try {
                throw new Exception("分母不可为0");
            } catch (Exception e) {
                e.printStackTrace();
            }        
        }
    }

猜你喜欢

转载自blog.csdn.net/SignalFire/article/details/105442616