2017-09-30 5 views
0

私は同じコンストラクタでこれらの例外を両方ともどのように実行できるのだろうと思いました。私のプログラムはうまくコンパイルされますが、2番目のif文の例外はスローされません。1つのコンストラクタに複数の例外をスローするにはどうすればよいですか?

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

できません。 1つの例外は最大です。 – user2357112

+0

すべての 'if/elseif/else'ステートメントの周りに' {} 'を置く方法を学んでください!いずれかの点が 'null'の場合、それは決してその行に到達しません。このコードには何も問題はありません。 –

+1

また、 'firstPoint == secondPoint'は参照equalityの比較であり、2つのオブジェクトが同じ位置を表すかどうかのテストではありません。 – user2357112

答えて

1

2つの例外をスローするとどういう意味ですか?スローした場合、メソッドが終了します。メッセージを結合する必要がある場合は、次のようなことができます。

//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); 
} 
関連する問題