Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, is using throws Exception instead of throwing multiple specific exceptions good practice?

While looking through the Spring MVC framework I noticed that, unless I misunderstand, its developers favor throws Exception instead of throwing multiple exceptions.

I realize that at the core of this question is the checked versus unchecked exceptions debate, avoiding that religious war, is it a good practice to use throws generic exception?

like image 533
James McMahon Avatar asked Jun 12 '09 13:06

James McMahon


People also ask

Is it good practice to throw exception in Java?

The short answer is NO. You would throw an exception if the application can't continue executing with the bad data. In your example, the logic is to display an error message on the front end and Option 2 is the cleaner method for achieving this requirement.

What is not a recommended practice for exception handling?

Don't Catch Throwable You can use it in a catch clause, but you should never do it! If you use Throwable in a catch clause, it will not only catch all exceptions; it will also catch all errors. Errors are thrown by the JVM to indicate serious problems that are not intended to be handled by an application.

Which of the following are the best practices for exception handling in Java?

First, unless you have very good reason, never catch RuntimeException , Exception or Throwable . These will catch most anything that is thrown, and Throwable will catch everything, even those things you're not meant to catch, like OutOfMemoryError .


1 Answers

No, absolutely not. You should specify what exceptions you're going to throw so the caller can do the right thing with each one. If you don't, "throws Exception" gets passed up the chain, and the best the callers can do is printStackTrace() and die.

Update: To counter some of the "what if I override the method" objections, I'd go a bit further and say that any time you have a package that throws exceptions (as opposed to passing up an exception from a caller), you should declare an exception class in that package. Thus, if you're overriding my "addToSchedule() throws ScheduleConflictException", you're perfectly able to subclass ScheduleConflictException to do what you need.

like image 197
Paul Tomblin Avatar answered Sep 30 '22 20:09

Paul Tomblin