首页 新闻 会员 周边

Java中,主动抛出运行时异常,最后异常由谁处理呢?

0
悬赏园豆:5 [已解决问题] 解决于 2022-02-17 13:32

如下代码:

public int getTotalPages(int rowsPerPage) {
    Connection conn;
    PreparedStatement pstmt;
    ResultSet rs;
    conn = ConnectionUtils.getConnection();
    try {
      pstmt = conn.prepareStatement(getTotalRows);
      rs = pstmt.executeQuery();
      rs.next();
      int totalRows = rs.getInt(1);
      if (totalRows % rowsPerPage == 0) {
        return totalRows / rowsPerPage;
      } else {
        return totalRows / rowsPerPage + 1;
      }
    } catch (SQLException e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }


  }

主动抛出运行时异常,可以不声明抛出异常,即可以不在方法签名处使用throws声明抛出异常,那么调用getTotalPages()时就可以不处理异常,那么请问当方法getTotalPages()真正抛出运行时异常时,最后是谁在处理这个异常呢?

比如我在main方法中调用方法getTotalPages():

public static void main(String[] args) {
    ProjectDAO pdao = new ProjectDAO();
    pdao.getTotalPages(5);
  }

结果真正抛出运行时异常了,但是在main方法中又没有try/catch,也没有声明抛出异常,那么方法getTotalPages抛出的异常最后是怎么处理的呢?

liaowenxiong的主页 liaowenxiong | 初学一级 | 园豆:33
提问于:2022-02-09 21:05
< >
分享
最佳答案
0

jvm 呀 !在真正的项目中遇到这种的运行时异常 要根据实际的业务逻辑 决定是把异常吃掉,还是终止业务。

收获园豆:3
agnils | 菜鸟二级 |园豆:205 | 2022-02-12 14:57
其他回答(3)
0

由Java运行时(runtime)处理

dudu | 园豆:30948 (高人七级) | 2022-02-09 21:10
0

我在RuntimeException类给你找到了它的介绍:
RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.
RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.
要不你仔细读一遍?

我是满意吖 | 园豆:386 (菜鸟二级) | 2022-02-10 14:57
1

这种异常,我们向外抛,抛到外层,还是通过自己代码去处理。不会完全依赖jvm去处理

收获园豆:2
宸钪 | 园豆:220 (菜鸟二级) | 2022-02-11 15:35
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册