java - 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
- add condition in scope of finally
- move declaration con varialbe to out of scrope.
It still cannot catch any exception
解决方案
该块中con
声明的变量try
超出了catch
andfinally
子句的范围。
该代码可以编译的唯一方法是如果您声明了另一个con
变量......可能作为封闭类的一个字段。
这解释了为什么当这显然不可能发生时,您会看到con
一个值。null
您正在打印另一个 con
变量。
请注意,DriverManager.getConnection(...)
永远不会返回null
。javadoc声明它返回一个对象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();
}
(如果您出于诊断目的捕获异常,则应始终打印或记录堆栈跟踪!)
推荐阅读
- url - 使用凭据创建 URL
- google-maps - 谷歌地图可以连接为 Mapbox-gl 基础层吗?
- python - 如何避免导入底图时出现 PROJ_LIB 错误?
- c# - 将 SeedData 注入自定义 WebApplicationFactory 的最佳方法
- django - 将 Docker 用于 Django 和 Channels 有什么好处?
- java - 如何将字符串设置为数组中的随机Textview?
- php - 如何从应用范围 ID 获取 Facebook 真实用户 ID
- python - 如何告诉 f2py 模块在当前目录中查找共享对象依赖项
- node.js - 使用 Node.js 实现通用 Web Scraper
- r - 重构二分法变量