首页 > 解决方案 > DriverManager.getConnection("url"); cannot catch any exception

问题描述

Android App is connected to database by using JDBC library. But DriverManager.getConnection("url") is returning null. So I tried putting "try...catch " like this:

      Connection con = null;
      try {

            con = DriverManager.getConnection("dummy url");
            System.out.println("Connected.");

      }catch(ClassNotFoundException ce){
            System.out.println("ClassNotFoundException ");
      }catch(SQLException se){
            System.out.println("SQLException ");
      }catch(Exception e){
             System.out.println("Exception ");
      }finally {
            if (con== null) {
               System.out.println("Result: null");
            }else{
               return con;
            }
      }

Output:

      Result: null

If URL is wrong , Try...Catch should be cached some exception. But it skipped all exceptions and getConnection("dummy url") returned null.

Although I tried to change to real url however the problem is not different.

Updated: I modified some code

  1. add condition in scope of finally
  2. move declaration con varialbe to out of scrope.

It still cannot catch any exception

标签: javajdbc

解决方案


该块中con声明的变量try超出了catchandfinally子句的范围。

该代码可以编译的唯一方法是如果您声明了另一个con变量......可能作为封闭类的一个字段。

这解释了为什么当这显然不可能发生时,您会看到con一个值。null您正在打印另一个 con变量。


请注意,DriverManager.getConnection(...)永远不会返回nulljavadoc声明它返回一个对象Connection,没有别的。如果方法可以返回null,文档会明确说明。


更新一旦你用 . 更正了范围界定问题con。现在问题可能是您没有捕获异常。具体来说,它可能是一个Error异常,如果加载(例如)适当的 JDBC 驱动程序类时出现问题,则可能会出现这种情况。

改变

  }catch(ClassNotFoundException ce){
        System.out.println("ClassNotFoundException ");
  }catch(SQLException se){
        System.out.println("SQLException ");
  }catch(Exception e){
         System.out.println("Exception ");

  } catch(Throwable e) {
         e.printStackTrace();
  }

(如果您出于诊断目的捕获异常,则应始终打印或记录堆栈跟踪!)


推荐阅读