异常处理和Throwable中的几个方法

package cn.lijun.demo;
/*
 * try {
//需要被检测的语句。
}
catch(异常类 变量) { //参数。
//异常的处理语句。
}
finally {
//一定会被执行的语句。
}
 * 
 * */
public class ExceptionDemo {
    public static void main(String[] args) {
        try {
            fun1(0);
        } catch (Exception ex) {
            System.out.println(ex);
            ex.printStackTrace();
        }finally{
            System.out.println("最终执行的代码");
        }
    }
    public static void fun1(int i) throws Exception{
        if(i==0)
            throw new Exception();
        System.out.println(i);
        
    }
}




package cn.lijun.demo;
/*运行异常  方法不需要throws语句  调用者不需要处理
 * 运行异常   不能发生  但是如果发生了  需要修改源代码
 * 运行异常一旦发生  后面的代码没有执行的意义
 * 
 * 
 * */
public class ExceptionDemo2 {
    public static void main(String[] args) {
        double d = getArea(-1);
        System.out.println(d);
    }
    /*定义一个方法计算圆形的面积
     *  
     * 
     * 
     * 1*/ 
    public static double getArea(double r){
        if(r<0)
            throw new RuntimeException("圆形不存在");
            return r*r*Math.PI;
        
    }
}


package cn.lijun.demo;
/*  Throwable类中的方法    都和异常信息有关
 * String getMessage()   对异常信息的详细描述
 * String toString()   对异常信息的简短描述
 * void printStackTrace()  异常信息最全的  jvm 默认调用的方法
 * 
 * */
public class ExceptionThrowAbleDemo {
    public static void main(String[] args) {
        try {
            fun();
            int i = 0;
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
    public static void fun() throws Exception{
        throw new Exception("异常了 下雨了");
    }
}

猜你喜欢

转载自www.cnblogs.com/qurui1998/p/10589708.html