1. 程式人生 > >try catch finally

try catch finally

cep throw sys out span all 信息 ice trace

lass Ff{
    
        int avg(int n1,int n2)throws  Exception{
            
            if (n1<0||n2<0) {                          //判斷方法參數是否滿足條件
            throw new  Exception("不能使用負數");          //錯誤信息
            }
            if (n1>100||n2>100) {
            throw new  Exception("數值太大了");
            }
            
return (n1+n2)/2; // 將參數的平均值返回 } } public class D27 { public static void main(String[] args) throws Exception { Ff f =new Ff(); System.out.println(f.avg(14, 10)); try{ System.out.println("
正確"); int a=1/0; System.out.println(a); }catch(Exception e){ System.out.println("Exception"); int c=1/1; System.out.println(c); e.printStackTrace(); } finally{ System.
out.println("finally"); } } }

結果:

12
正確
Exception
1
java.lang.ArithmeticException: / by zero
at com.zhongguo.javase.D14.D27.main(D27.java:28)
finally

try catch finally