JDBC Exception Handling

I have a servlet program written but am wondering if exceptions are being handled correctly.

Which is better to use if you're connecting to an oracle database in a jdbc program?

Does it make a difference if you use catch(SQLException) instead of catch(Exception)?

Edit/Delete Message

[309 byte] By [scorpion2a] at [2007-11-27 9:06:32]
# 1

> Which is better to use if you're connecting to an

> oracle database in a jdbc program?

Huh? It has nothing to do with Oracle or JDBC, it's just good programming style.

> Does it make a difference if you use

> catch(SQLException) instead of catch(Exception)?

Sure. One catches all types of exceptions, the other only SQLExceptions, which of course should *always* be preferred.

CeciNEstPasUnProgrammeura at 2007-7-12 21:42:07 > top of Java-index,Java Essentials,Java Programming...
# 2

Would this kind of code(pseudo) handle an exception correctly?

public void dbmethod(string a,stringb) throws SQLException

{

try

{

connect tp database and other stuff

}

catch(SQLException sqle)

{

throw sqle;

}

finally

{

close resultset;

close statements;

close connection;

}

}

scorpion2a at 2007-7-12 21:42:07 > top of Java-index,Java Essentials,Java Programming...
# 3
No. It doesn't handle anything. That catch block is pointless. http://java.sun.com/docs/books/tutorial/essential/exceptions/
CeciNEstPasUnProgrammeura at 2007-7-12 21:42:07 > top of Java-index,Java Essentials,Java Programming...
# 4

> Would this kind of code(pseudo) handle an exception

> correctly?

> [code]

> public void dbmethod(string a,stringb) throws

> SQLException

> {

>try

>

> connect tp database and other

> stuff

>

> catch(SQLException sqle)

> {

> throw sqle;

> y

> {

>close resultset;

> close statements;

>close connection;

> ode]

Not really. Why does it catch and then simply re-throw the exception? You'll be propagating exception code to other methods, when your method could simply handle it itself.

You could have the method catch SQLExceptions and throw some subclass of RuntimeException, if there's nothing sensible your code can do to recover from the exception. There often isn't. What can you reasonably expect to do to carry on working when your database calls are failing? Not much

georgemca at 2007-7-12 21:42:07 > top of Java-index,Java Essentials,Java Programming...
# 5
How about I put a println statement in the catch instead?System.out.println(sqle)would that be better?
scorpion2a at 2007-7-12 21:42:07 > top of Java-index,Java Essentials,Java Programming...
# 6

> How about I put a println statement in the catch

> instead?

> System.out.println(sqle)

>

> would that be better?

Why would that be better? How would that help handle the exception? How will it help the user? Will it even be seen? Simply observing an exception is not handling it

georgemca at 2007-7-12 21:42:07 > top of Java-index,Java Essentials,Java Programming...