java异常

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.Lucky.oop;
 
import java.io.IOException;
 
import static com.Lucky.oop.DefindsException.Add;
 
/*
异常:
           throwAble:  error 与 exception
           Error:由java虚拟机生成并且抛出,大多数错误与编写者的操作无关
                  例如:OutOfMemoryError[内存溢出] 或 NoClassDefFoundError
                       或 LinkageError[连接错误]
 
           exception:关键字:try catch finally throw throws
            IOException[IO异常]
                      例如:FileNoFoundException[文件找不到异常]
                           …………………………
            runtimeException[运行时异常]
                      例如:ArrayIndexOutOfBoundsException[数组下标越界异常]
                           NullPointerException[空指针异常]
                           ArithmeticException[算术异常]
                           ClassNoFoundException[找不到类异常]
                           …………………………
 
 
    每天小知识:ctrl+alt+T :生成常用的判断
 
 */
public class ExceptionClass {
 
    public static void main(String[] args) {
 
        try{   //监控区
 
        }catch (ArithmeticException e){
             ////要捕获的异常:从小到大,不然大的异常就包括小的异常了,将无法捕获小的异常了
           //      ArithmeticException<Exception<Throwable
        }catch (Exception u){
            u.printStackTrace(); //异常信息
        }catch (Throwable e){
        }finally //finally :常用于  IO,资源关闭
            System.out.println("finally最后执行的【必然会执行的】");
        }
 
 
        String strA="病毒警告";
        try {
            Add(strA);
        } catch (DefindsException e) {
            e.printStackTrace();
        } finally {
        }
 
 
    }
 
 
}

  自定义异常:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.Lucky.oop;
/*
自定义异常:只要继承Exception即可
 */
public class DefindsException extends Exception{
 
    private String message;
 
 
      //相当于有参构造器
    public  DefindsException(String message) {
        this.message = message;
    }
 
    //异常处理方法
    public static void Add(String str)throws DefindsException{
        if(str=="病毒警告"){
            throw new DefindsException(str);
        }
        System.out.println("ok");
    }
 
 
    @Override
    public String toString() {
        return "DefindsException{" +
                "message='" + message + '\'' +
                '}';
    }
}

  

posted @   唯易人生  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示