When is it appropriate to throw an exception?

I recently saw some kind of code when the author threw exceptions for almost every constructor and threw exceptions to do things like the code below in a method that returns an int:

if(condition){
  return 1;
}
if(condition){
  return 2;
}
if(condition){
  return 3;
}
throw new RuntimeException("Unreachable code");
// method ends here

I personally would not choose an exception, because I would structure it using the if and else if statements, and in this particular case your code would be fundamentally wrong so that it does not satisfy any of the conditions. / p>

There are many places where you could throw exceptions at runtime that will never be reached if you work correctly, sometimes it seems that the author does not trust the code to work, in the case of the code block above. In addition, each constructor can throw an exception if it is not initialized correctly, but you can also structure it so that the object is empty - for example, you could check it basically.

What do I ask mainly when it is worth throwing an exception?

+4
source share
2 answers

The exception point is the transfer of exceptional situations.

: , , , RuntimeException ; , , :

throw new RuntimeException("All conditions failed: " + some data)

: ; , . , , false.

, ; . : , , @throws RuntimeException .

RuntimeException ; .

: , . : :

public class Whatever {
  private final Foo theFoo;

  public Whatever(Foo theFoo) {
   Objects.requireNonNull(theFoo, "theFoo must not be null");
   this.theFoo = theFoo;

, NPE, ; . : . , ; , .

: ; "" : , ; , , .

; - - . - , - ! , : . , , " ". , , : !

+4

GhostCat , , . , . , , - , . , . ( , , , , ++). , , :

1- ;

2- ;

3 - ;

4- , assert preprocessor. , 4- ;

5 , Unit Test, , . /

6- , , , , , , .

7- , ... , , , .

-1

Source: https://habr.com/ru/post/1673996/


All Articles