首页 > 代码库 > try catch finally

try catch finally

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