• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Writting logic in catch block

 
Varadhan Sesharaman
Ranch Hand
Posts: 30
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,

Can we write logic in catch block.

Suppose we establish db connection in try block and then due some exception the try block is terminated and can we close the connection it in catch block.

If not possible i need a reason for that.


Thanks,
varadhan.s
 
Winston Gutkowski
Bartender
Pie
Posts: 10527
64
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Varadhan Sesharaman wrote:Can we write logic in catch block.

Not only can you; you should. Empty catch blocks are evil.

Suppose we establish db connection in try block and then due some exception the try block is terminated and can we close the connection it in catch block.

It depends. Did the try block actually open the connection? If so, then obviously the error resulted from something else and you need to decide whether you can continue; if not, chances are that trying to close a connection that isn't open will generate another error.

Winston
 
Anayonkar Shivalkar
Bartender
Posts: 1557
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Varadhan Sesharaman wrote:Hi guys,

Can we write logic in catch block.

Suppose we establish db connection in try block and then due some exception the try block is terminated and can we close the connection it in catch block.

If not possible i need a reason for that.


Thanks,
varadhan.s

Sure, we can write logic inside catch block.

However, the code enters in catch block due to exception, right? So, as a part of good coding practice, whenever possible, catch block should be dealing only with handling/re-throwing of exception (e.g. analyzing the exception and logging proper error message etc.)

But, please make sure that try-catch block should not be used as a substitute to if-else statement.
e.g.

is much better than

Particularly for DB connection, I would suggest to close it in finally block (instead of catch block). Because, what if you close it in catch block, and what if exception doesn't occur? So, better approach would be to put 'cleanup' part (closing ResultSet, Connection etc.) in finally block.

However, as Winston has suggested, don't forget to check whether connection was opened in first place - otherwise you'll end up closing an unopened connection - which will lead to another exception

And, I would (again) agree with Winston. Below code is a short-cut to become an unpopular developer:

I hope this helps.
 
Varadhan Sesharaman
Ranch Hand
Posts: 30
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you guys.

Now i got it cleared.

Thanks again for your help
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic