2017-09-30 1 views
0

Je me demandais comment puis-je exécuter ces deux exceptions dans le même constructeur. Mon programme compile bien, mais il ne lancera pas l'exception pour la seconde instruction if.Comment lancer plusieurs exceptions dans un constructeur?

public Segment(Point firstPoint, Point secondPoint) { 
    if(firstPoint == null || secondPoint == null) 
     throw new IllegalArgumentException("Cannot pass a null value"); 
    if(firstPoint == secondPoint) 
     throw new IllegalArgumentException("Segment cannot be 0"); 

    this.endPoint1 = new Point(firstPoint); 
    this.endPoint2 = new Point(secondPoint); 
} 
+0

Vous ne pouvez pas. Une exception max. – user2357112

+0

apprenez à mettre '{}' autour de TOUTES les instructions 'if/elseif/else'! Si l'un des points est 'null', il n'atteindra jamais cette ligne. Il n'y a rien de mal avec ce code. –

+1

De plus, 'firstPoint == secondPoint' est une comparaison d'égalité de référence, pas un test pour savoir si les deux objets représentent la même position. – user2357112

Répondre

1

Que voulez-vous dire en lançant deux exceptions? Si vous faites throw, la méthode s'arrête. Si vous avez besoin de combiner des messages, vous pouvez faire quelque chose comme ceci:

//Parameterized constructor 
public Segment(Point firstPoint, Point secondPoint) 
{ 
    String error = ""; 
    if(firstPoint == null || secondPoint == null) { 
     error = "Cannot pass a null value"; 
    } 
    if(firstPoint == secondPoint) { 
     error = error.equals("") ? 
       "Segment cannot be 0" : 
       error + ". Segment cannot be 0" 
    } 

    if (!error.equals("")){ 
     throw new IllegalArgumentException("Segment cannot be 0"); 
    } 

    this.endPoint1 = new Point(firstPoint); 
    this.endPoint2 = new Point(secondPoint); 
}