1. 程式人生 > 實用技巧 >java異常使用

java異常使用

一、try-catch-finaly處理

//當場捕捉處理處理異常
public void testTryCatch(){
       try {
           logger.info("1/0={}",1/0);
       }catch (ArithmeticException  e){
           logger.info("捕捉異常{}",e.getMessage());
       }catch (Exception e){
           logger.info("捕捉異常{}",e.getMessage());
       }finally{
           logger.info("方法結束");
       }
    }
//
  static private void test(){
        UserExceptionTest e = new UserExceptionTest();
        e.testTryCatch();
    }

二、使用throw丟擲異常,外層呼叫處理該異常

//自定義異常
public class UserException extends Exception{
    private String msg;
    private String location;
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
}
//丟擲異常
 public void testThrowsExp() throws UserException {
        int m = 0;
        if(m==0){
            UserException e=new UserException();
            e.setLocation(e.getClass().getName());
            e.setMsg("除數不能為0!");
            throw e;
        }else{
            logger.info("1/m={}",1/m);
        }
    }
//捕捉異常並處理
 static private void test1(){
        try{
            UserExceptionTest e = new UserExceptionTest();
            e.testThrowsExp();
        }catch (UserException e){
            logger.info("捕捉異常{}:{}",e.getMsg());
            logger.info("異常:{}",e.getLocation());
        }finally {
            logger.info("方法結束");
        }
    }