Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

About catching Exception instead of more specific exception.

 
Olena Golub
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Everybody,

I am a little bit confused about exception handling. I have some question about it and I would very appreciate if you can help me!

1. If I have a method, that throws more than one exception. What is the right way to handle these exceptions? For example:
For Naming.lookup(�) there are three defined exception. What is the correct way to handle it? Catch every exception:


or catch only the main Exception:



2. Are there are some books, links with something like "best practice". Could you recommend me?

Thanks a lot for your help!!!

Regards,
Olena.
 
Wei-ju Wu
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Olena,

there is a book that every Java developer should have which is "Effective Java" by Joshua Bloch. This also handles the topic of handling exceptions appropriately. In this case my guess would be that the topic "throw exceptions appropriate to the abstraction" would be a good start.

However, you need to regard the method where you handle these exceptions in the context of your application and decide which of the recommendations fits you best.

Wei-ju
 
Mihai Radulescu
Ranch Hand
Posts: 918
IntelliJ IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Olena,

In geneal is bad to catch the Exception exception because the Exception is the super(parent) class for all the exceptions runtime or not so you catch all and you can not make a distionction between the them.
But sometimes the runtime exceptions means a promming(logic) error and it better to let them to occur from beginig.

Mihai.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic