Java
1class InvalidIdException extends Exception { } 2class MissingNameException extends Exception { } 3class Patron { 4 private int id; 5 private String name; 6 public Patron(int id, String name) throws Exception { 7 if (id < 1) { 8 throw new InvalidIdException(); 9 } else if (name == null) { 10 throw new MissingNameException(); 11 } else { 12 this.id = id; this.name = name; 13 } 14 } 15 public String toString() { 16 return " [ " + id + " : " + name + " ] "; 17 } 18} 19public class Owner { 20 //public static void main(String[] args) { // 1.add throws declaration 2.surround with try/catch 21 public static void main(String[] args) throws Exception { 22 Patron p1 = new Patron(101, "Beethoven"); 23 Patron p2 = new Patron(102, "Mozart"); 24 System.out.print(p1); 25 System.out.print(p2); 26 } 27}
ある問題集のスクリプトですが、throws を書いているのに catch がないのですが、エラーなく実行できてしまいます。
throw して throws して、それを catch するものがなくてもエラーがないというところが、どう考えたら良いものかわかりません。
必ずしも catch は必要ではないということなのでしょうか?

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/02/19 14:14 編集