ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

异常处理

2021-09-08 16:03:27  阅读:189  来源: 互联网

标签:处理 System finally println 异常 public out


异常处理机制

  • 抛出异常

  • 捕获异常

异常处理五个关键字

  • try、catch、finally、throw、throws

try catch finally

 package oop.Exception;
 ​
 public class Test {
     public static void main(String[] args) {
         int a = 1;
         int b = 0;
         try {//try监控区域是否有异常
             System.out.println(a/b);
        }catch (ArithmeticException c){//捕获异常,如果异常则执行
             System.out.println("程序出现异常");
        }finally {//出不出异常都会执行
             System.out.println("finally");
        }
 ​
    }
 }
 ​

finally可以不要,假设IO、资源需要关闭,关闭操作可以放在finally里

捕获Error:

 package oop.Exception;
 ​
 public class Test {
     public static void main(String[] args) {
         int a = 1;
         int b = 0;
         try {//try监控区域是否有异常
             new Test().a();
        }catch (Throwable c){//捕获异常,如果异常则执行,throwable级别最高,能捕获所有异常
             System.out.println("程序出现异常");
        }finally {//出不出异常都会执行
             System.out.println("finally");
        }
 ​
    }
     public void a(){
         b();
    }
     public void b(){
         a();
    }
 }

可以有多个catch,但捕获级别要从小到大

 package oop.Exception;
 ​
 public class Test {
     public static void main(String[] args) {
         int a = 1;
         int b = 0;
         try {//try监控区域是否有异常
             new Test().a();
        }catch (Error c) {//捕获异常,如果异常则执行
             System.out.println("Error");
        }
             catch (Exception d){
                 System.out.println("Exception");
            }
             catch (Throwable e){
                 System.out.println("Throwable");
            }
         finally {//出不出异常都会执行
             System.out.println("finally");
        }
 ​
    }
     public void a(){
         b();
    }
     public void b(){
         a();
    }
 }

throw和throws

 package oop.Exception;
 ​
 public class Test {
     public static void main(String[] args) {
         try {
             new Test().a(1,0);
        } catch (ArithmeticException e) {
             e.printStackTrace();
        }
 ​
    }
     //假设这个方法中处理不聊这个异常。方法上抛出异常
     public void a(int x,int y) throws ArithmeticException{
         if(y==0){//主动抛出异常 throw   throws
             throw new ArithmeticException();//一般在方法中使用
        }
         System.out.println(x/y);
    }
 ​
 }

 

标签:处理,System,finally,println,异常,public,out
来源: https://www.cnblogs.com/scxgy/p/15243104.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有