Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...