java异常处理throws与throw与assert

throws、throw、assert关键字

throws:作用于方法上

在进行方法定义时候,如果要明确告诉调用者本方法可能产生哪些异常,可以使用throws方法进行声明,表示将异常抛回给调用方。并且当方法出现问题后可以不进行处理。

 public static int calculate(int x,int y) throws Exception {
        return x / y;
 } 

但用了throws的方法被调用时,必须用try……catch包围,因为他可能出错,或者在主方法中也throws这个错误,抛给jvm处理:

public static void main(String[] args) throws Exception{
    System.out.println(calculate(10, 0));
}

//或者这样
public static void main(String[] args) {
    try {
        System.out.println(calculate(10, 0));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

throw:一般与自定义异常类搭配使用

 public static void main(String[] args){
    try {
        throw new Exception("抛个异常") ;
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 

assert:断言

用来判断走到这一步的时候,这个值是不是你希望的正确值:

Assert num == 5 : “应该是55”;
//如果num不是5,就会出错,然后提示应该是55,其实和if差不多

猜你喜欢

转载自blog.csdn.net/likunkun__/article/details/83685992
今日推荐