Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Java
  3. Question
Java

Why shouldn't Java throw multiple exceptions?

Asked by Leonard Terry Oct 11, 2022 1.5K views 1 answer
Share

About this question

We use SonarQube to analyze our Java code and it has this rule (set to critical):


Public methods should throw at most one checked exception

Using checked exceptions forces method callers to deal with errors, either by propagating them or by handling them. This makes those exceptions fully part of the API of the method.


To keep the complexity for callers reasonable, methods should not throw more than one kind of checked exception."


Another bit in Sonar has this:


Public methods should throw at most one checked exception

Using checked exceptions forces method callers to deal with errors, either by propagating them or by handling them. This makes those exceptions fully part of the API of the method.


To keep the complexity for callers reasonable, methods should not throw more than one kind of checked exception.


The following code:


public void delete() throws IOException, SQLException {      // Non-Compliant
  /* ... */
}
should be refactored into:
public void delete() throws SomeApplicationLevelException {  // Compliant
    /* ... */
}

Overriding methods are not checked by this rule and are allowed to throw several checked exceptions.


I've never come across this rule/recommendation in my readings on exception handling and have tried to find some standards, discussions etc. on the topic. The only thing I've found is this from CodeRach: How many exemptions should a method throw at most?

Is this a well accepted standard?

Your answer

1 Answer

More Java discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Java Blogs

Guides, tips and career advice on Java from JanBask experts.