前提
javaで別パッケージのnull判定文に従ってtry-catchで例外処理を行いたいと考えています。
自作クラスなどについては、クラス名の前にパッケージ名をつけることで引き継ぐことができたのですが、catch文の部分だけ例外処理を引き継ぐことができなくて困っています。
先頭にimport文などを置くなどする必要があるのでしょうか?それともそもそも引き継ぐことはできずもう一度該当パッケージ内で例外処理の文を書き直す必要があるのでしょうか?
ご教授いただきたいです。コードが汚く理解しづらい点があると思いますがよろしくお願いします。
ディレクトリは下記の通りです。
Stage
・test1→Bond.java
・test2→BondTest.java
実現したいこと
- パッケージtest1にあるコンストラクタBondのcodeの引数がnullの時、IllegalArgumentExceptionを用いてnull判定を行う処理をパッケージtest2のBondクラスのcatch処理に引き継ぐ
該当のソースコード
Java
1package test1; 2 3import java.util.Objects; 4 5public class Bond { 6 private String code; 7 private String name; 8 private int maturity; 9 private double coupon; 10 private String BondType; 11 12 public Bond (String code, String name, int maturity, double coupon) { 13 this.code = code; 14 this.name = name; 15 this.maturity = maturity; 16 this.coupon = coupon; 17 } 18 //getter 19 public String getCode() { 20 return this.code; 21 } 22 public String getName() { 23 return this.name; 24 } 25 public int getMaturity() { 26 return this.maturity; 27 } 28 public double getCoupon() { 29 return this.coupon; 30 } 31 public String getBondType() { 32 if (coupon == 0) { 33 BondType.equals("ZERO_COUPON_BOND"); 34 } else { 35 BondType.equals("COUPON_BOND"); 36 } 37 return this.BondType; 38 } 39 40 @Override 41 public String toString() { 42 StringBuilder builder = new StringBuilder(); 43 builder.append(code); 44 builder.append(name); 45 builder.append(maturity); 46 builder.append(coupon); 47 builder.append(BondType); 48 return builder.toString(); 49 } 50 51 //equalsメソッド 52 @Override 53 public boolean equals (Object obj) { 54 if (this == obj) { 55 return true; 56 } 57 if (obj == null) { 58 return false; 59 } 60 if (getClass() != obj.getClass()) { 61 return false; 62 } 63 Bond other =(Bond)obj; 64 if (this.code != other.code) { 65 return false; 66 } 67 if (maturity == 0) { 68 if (other.maturity != 0) { 69 return false; 70 } 71 } else if (maturity != other.maturity) { 72 return false; 73 } 74 if (Double.compare(other.coupon,coupon) != 0) { 75 return false; 76 } 77 // チェック処理 78 if (code == null || name == null) { 79 throw new IllegalArgumentException("nullです。"); 80 } 81 if (maturity < 20000101 || 29991231 < maturity || coupon < 0) { 82 throw new IllegalArgumentException("数値が範囲外です"); 83 } 84 return true; 85 } 86 87 //hashCode 88 @Override 89 public int hashCode() { 90 return Objects.hash(this.code, this.maturity, this.coupon); 91 } 92} 93 94 95package test2; 96 97public class BondTest { 98 public static void main (String [] args) { 99 try { 100 test1.Bond bond2 = new test1.Bond(null, "name", 20220810, 1); 101 System.out.println(bond2); 102 } 103 catch (IllegalArgumentException e ) { 104 System.out.println("入出力エラーです。"); 105 } 106 } 107}
試したこと
catchをtest1.IllegalArgumentExceptionとした場合シンボルが見つからずそもそもコンパイルができなかった。
回答1件
あなたの回答
tips
プレビュー