Java面向对象8-异常

 

一、异常的体系结构:

  

java.lang.Throwable

  |-----java.lang.Error:一般不编写针对性的代码进行处理

  |-----java.lang.Exception:可以进行异常的处理

    |-----编译时异常(checked)

      |-----IOException

         |-----FileNotFoundException

      |-----ClassNotFoundException

    |-----运行时异常(unchecked,RuntimeException)

      |-----NullPointerException

      |-----ArrayIndexOutOfBoundsException

      |-----ClassCastException

      |-----NumberFormatException

      |-----InputMismatchException

      |-----ArithmeticException

 

二、异常的处理方式

  ①try-catch-finally 真正的处理了异常

  ②throws + 异常类型,写在方法的声明处,只是将异常抛给了方法的调用者

 

三、开发中如何选择try-catch-finally和throws

  3.1如果父类中被重写的方法没有throws方式处理异常,则子类重写的方法也不能使用throws,意味着如果子类重写的方法中有异常,必须使用try-catch-finally方式处理

  3.2执行的方法a中,先后调用了另外的几个方法,这几个方法是递进关系执行的,建议这几个方法使用throws的方式进行处理。而执行的方法a可以考虑使用try-catch-finally

 

四、手动抛出异常对象

  

throw new RuntimeException("运行时异常");

 

 

 

throw new Exception("异常");

 

五、自定义异常

extend Exception

 

 

异常代码实例:

复制代码
 1 public class EcmDef {
 2     public static void main(String[] args) throws ArrayIndexOutOfBoundsException{
 3 
 4         EcmDef test = new EcmDef();
 5 
 6         try{
 7             int a = Integer.parseInt(args[0]);
 8             int b = Integer.parseInt(args[1]);
 9 
10             int result = test.ecm(a, b);
11         }catch(NumberFormatException e){
12             System.out.println("数据类型不一致");
13         }catch (ArrayIndexOutOfBoundsException e){
14             System.out.println("缺少命令行参数");
15         }catch (ArithmeticException e){
16             System.out.println("除 0");
17         } catch(EcDef e) {
18             throw new RuntimeException(e);
19         }
20 
21 
22 
23     }
24 
25     public int ecm(int a, int b) throws EcDef{
26         if(a < 0 || b < 0){
27             throw new EcDef("分子或分母为负数了");
28         }
29         return a / b;
30     }
31 }
32 public class EcDef extends Exception{
33     static final long serialVersionUID = -3387516993124229949L;
34 
35     public EcDef(){}
36 
37     public EcDef(String msg){
38         super(msg);
39     }
40 
41 }
复制代码

 

posted @   草莓小甜心  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示