throw Exception

public class ExceptionTest {
    public static void main(String[] args){

        try{
            throwException();
            System.out.println("throw 后面");//此处不会打印
        }catch (Exception e){
            System.out.println("捕获啦~~~");
//            return;//加上return后,后面的打印直接编译报错。
//            throw new RuntimeException("throw出去");//加上throw后,后面的打印直接编译报错。
        }

        System.out.println("catch捕获exception后,如果没有throw 或return,是会继续执行,此处log会被打印。");

        throwException();
        System.out.println("throw 后面");//此处不会打印

        Product p = null;
        System.out.println(p.toString());//报错:Exception in thread "main" java.lang.NullPointerException
    }
    /**
     * 捕获啦~~~
     * catch捕获exception后,如果没有throw 或return,是会继续执行,此处log会被打印。
     */

    private static void throwException() {
        throw new RuntimeException("出错啦!");
    }
}
try{
     throw new RuntimeException("出错啦!");
     System.out.println("throw 后面");//此处直接编译报错
}catch (Exception e){
     System.out.println("捕获啦~~~");
}

猜你喜欢

转载自blog.csdn.net/qq_38384102/article/details/83892662