Javaを勉強していて、一点どうしても疑問に思うことがあります。
Exception をcatchした際に、
throw exとするのと、throw new XXXExceptionとするのは
どのように違いますか?
呼び出し元に返すオブジェクトが違うということはなんとなく分かるのですが、
正確に使い分けることができません。
例えば、getAmt()というテーブルのデータを取得するメソッドがあるとした場合、
呼び出し元の処理は、
methodA、B、Cのうちどれが正しい記述でしょうか?
java
1 2import java.sql.SQLException; 3 4public class sample{ 5 public static void main(String [] args){ 6 try{ 7 methodA(); 8 methodB(); 9 methodC(); 10 }catch(SQLException ex){ 11 System.out.println(ex.getMessage()); 12 System.out.println(ex.getCause()); 13 } 14 15 } 16 17 private static int methodA() throws SQLException{ 18 int amt = 0; 19 20 AmtTable amtTable = new AmtTable(); 21 22 try{ 23 amt = amtTable.getAmt(); 24 }catch(SQLException ex){ 25 System.out.println("methodAでエラー"); 26 throw new SQLException(ex); 27 } 28 29 return amt; 30 } 31 32 private static int methodB() throws SQLException{ 33 int amt = 0; 34 35 AmtTable amtTable = new AmtTable(); 36 amt = amtTable.getAmt(); 37 38 return amt; 39 } 40 41 private static int methodC() throws SQLException{ 42 int amt = 0; 43 AmtTable amtTable = new AmtTable(); 44 try{ 45 amtTable.getAmt(); 46 amt = amtTable.getAmt(); 47 48 }catch(SQLException ex){ 49 System.out.println("methodCでエラー"); 50 throw ex; 51 } 52 53 54 return amt; 55 } 56}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/08/30 05:08
2019/08/30 05:11