Java Exception和Assertion

Exception分两类

  • RuntimeException及其子类,可以不明确处理
  • checked Exception受检异常

受检异常需 要明确进行语法处理

  • 要么捕(catch)

  • 要么抛(throws):在方法后用throws xxxx来声明

    //声明
    public static void readFile()throws IOException {
        ...
    }
    
    //调用
    public static void main(String[] args) {
        try{
            readFile();
        }catch(IOException e) {
            System.out.println(e);
        }
    }
    

自定义异常

class BankATM {
    public static void GetBalanceInfo(long ID)throws MyAppException 
    {
    	try {
            DataHouseException.FindData(ID)''
        }catch(DataHouseException e){
            throw new MyAppException("invalid id", e);
        }
    }
}

class DataHouseException extends Exception {
    //构造方法
    public DataHouseException(String message) {
        super(message);
    }
}

断言(assert)

如果不满足条件就发出异常,后面的代码也不会运行

格式:
assert 表达式
assert 表达式 : 信息;

Notice:编译器需要手动开启assert

public static void main(String[] args) {
    assert whatFuck(3,4)==5 : "FUCK";
}
static int whatFuck(int a, int b) {
    return a*b ;
}

/*Exception in thread "main" java.lang.AssertionError: FUCK at Machine.main(Machine.java:6)*/

throw和throws

方法内throw什么什么异常

方法 throws xxxx异常
public findError throws IOException{}

posted @ 2021-06-15 19:03  巴伐利亚药水哥  阅读(188)  评论(0)    收藏  举报