Reputation: 1038
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
It still cannot catch any exception
Upvotes: 1
Views: 2383
Reputation: 718788
That con
variable declared in the try
block is out of scope in the catch
and finally
clauses.
The only way that this code could compile is if you have declared another con
variable ... probably as a field of the enclosing class.
This explains why you are seeing con
with a null
value when that apparently cannot happen. You are printing the other con
variable.
Note that DriverManager.getConnection(...)
won't ever return null
. The javadoc states that it returns a Connection
object, and nothing else. If the method could return null
, the documentation would say so explicitly.
UPDATE Once you have corrected the scoping problem with con
. It is now possible that the problem is that you are not catching the exception. Specifically, it could be an Error
exception, which might arise if there was a problem loading (say) the appropriate JDBC driver class.
Change
}catch(ClassNotFoundException ce){
System.out.println("ClassNotFoundException ");
}catch(SQLException se){
System.out.println("SQLException ");
}catch(Exception e){
System.out.println("Exception ");
to
} catch(Throwable e) {
e.printStackTrace();
}
(If you catch an exception for diagnostic purposes, you should always print or log the stacktrace!)
Upvotes: 3