六、异常处理机制

抛出异常

public class Demo02 {
    public static void main(String[] args) {
        Demo02 demo02 = new Demo02();
        try {
            demo02.division(1,0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }
    }


    //加入在这个方法上处理不了这个异常,则在方法上通过throws关键字抛出异常
    int division(int a,int b) throws ArithmeticException{
        if (b==0){
            throw new ArithmeticException("被除数不可以为0");
        }
        return a/b;
    }
}

 

捕获异常

public class Demo01 {
    public static void main(String[] args) {
        int a=1;
        int b=0;
        try {
            //监控区
            System.out.println(a/b);
        }catch (Error e){
            System.out.println("Error");
            System.out.println(e.getMessage());
        }catch (Exception e){
            System.out.println("Exception");
            System.out.println(e.getMessage());
        }catch (Throwable e){
            System.out.println("Throwable");
            System.out.println(e.getMessage());
        }finally {
            //可以不写,但有时候会有一些关闭资源等操作。
            System.out.println("finally");
        }
    }
}

 

异常处理五个关键字

  • try
  • catch
  • finally
  • throw
  • throws

 

 

try和try()对比:

//try(){}
try (Connection c = DbUtil.getConnection();Statement createStatement = c.createStatement();)
{
    String sql = "select count(*) from config";
    ResultSet executeQuery = createStatement.executeQuery(sql);
    while(executeQuery.next())
    {
        total = executeQuery.getInt(1);
    }
}catch (Exception e) {
    throw new RuntimeException(e);
}



//try{}
Connection c = null;
try {
    c = DbUtil.getConnection();
    Statement createStatement = c.createStatement();
    String sql = "select count(*) from config";
    ResultSet executeQuery = createStatement.executeQuery(sql);
    while (executeQuery.next()) {
        total = executeQuery.getInt(1);
    }
}catch (Exception e) {
    throw new RuntimeException(e);
} finally {
    if (c != null) c.close();
}

总结:try()这种方式会自动调用关闭资源的方法,不需要显示地关闭资源。

posted @ 2022-05-13 20:46  Epiphany8Z  阅读(21)  评论(0编辑  收藏  举报