try、catch、finally中return的执行顺序及自定义异常创建

1.在Java中使用 try/catch语句捕获异常

说明

throw和throws的区别?

1.作用不同:throw用于程序员自行产生并抛出异常,throws用于声明该方法内抛出了异常。

2.使用的位置不同:throw位于方法体内部,可以作为单独语句使用。throws必须跟在方法参数列表的后面,不能单独使用。

3.内容不同:throw抛出一个异常对象,并且只能是一个。throws后面跟异常类,并且可以跟多个异常类。

try、catch、finally中return的执行顺序

上代码

package concurrent;

public class Test1 {
    public static void main(String[] args) {
        try{
            System.out.println("1");
            int x = 5;
            int y = 0;

            if(y==0){
                throw  new Exception("除数不能为0!");//当执行这句语句时,直接进入catch块
            }
           // int result = x/y;
            System.out.println("2");
        }
        catch(Exception e){
            System.out.println("3");
            e.printStackTrace();
            System.out.println("4");

        }
        finally{
            System.out.println("5");
        }
        System.out.println("6");
    }
}

注:无论哪个语句块中有return语句,都会执行finally语句块,而且如果finally 中语句块中含有return语句那么将会覆盖try  catch中的return语句

2.创建自定义异常

1).定义自定义异常,并继承Exception或者RuntimeException

扫描二维码关注公众号,回复: 4137211 查看本文章

2).编写异常类的构造方法,并继承父类的实现,常见的构造方法有4种。

package concurrent;

/**
 * @Author: hg
 * @Date: 2018/11/15 21:47
 * @Version 1.0
 */
public class CostomException extends Exception{

    public CostomException() {
        super();
    }

    public CostomException(String message) {
        super(message);
    }

    //用指定原因构造一个新的异常
    public CostomException(Throwable cause) {
        super(cause);
    }

    // 用指定的详细信息和原因构造一个新的异常
    public CostomException(String message, Throwable cause) {
        super(message, cause);
    }
}


class Test2{

    public static void setSex(String sex) throws CostomException {
        if(!"男".equals(sex)||!"女".equals(sex)){
            throw new CostomException("性别必须是男或女");
        }else{
            System.out.println("性别是:"+sex);
        }
    }

    public static void main(String[] args) {
        try {
            Test2.setSex("aa");
        } catch (CostomException e) {
            e.printStackTrace();
        }
    }

}

猜你喜欢

转载自blog.csdn.net/nameIsHG/article/details/84111345
今日推荐