try/catchの使い方なのですが。
下記はファイルをコピーペーストする関数になります。
処理が正常に行われたかを判断するためにtry/catchを使用したのですが、行数が倍くらいになりました。
処理結果が判断できて、かつ行数の少ない記述を考えています。
下記の様な行数の減らし方は思いつきました。
・部分的にtry/catchを使用する。
・void型にして関数の呼び出し元でtry/catchを使用する。
・この関数に限って言えば、try/catchなしの関数を使用して、下記を追記する。
java
1if(!new File(pathTo).exists()){処理}
2番目が妥当でしょうか。
それとも可読性よりは機能性を優先した方が良いでしょうか。
try/catchなし
java
1 //ファイルコピー・貼り付け(try/chatchなし) 2 private boolean CopyPaste(String pathFrom, String pathTo) throws IOException { 3 4 //コピー元 5 FileInputStream fileIn = new FileInputStream(pathFrom); 6 7 //コピー先 8 FileOutputStream fileOut = new FileOutputStream(pathTo); 9 10 // byte型の配列を宣言 11 byte[] buf = new byte[256]; 12 int len; 13 14 // ファイルの終わりまで読み込む 15 while((len = fileIn.read(buf)) != -1){ 16 fileOut.write(buf,0,len); 17 } 18 19 //ファイルに内容を書き込む 20 fileOut.flush(); 21 22 //ファイルの終了処理 23 fileOut.close(); 24 fileIn.close(); 25 26 return true; 27 }
try/catchあり
java
1 //ファイルコピー・貼り付け(try/catchあり) 2 private boolean CopyPaste(String pathFrom, String pathTo) { 3 4 boolean bl = false; 5 6 FileInputStream fileIn = null; 7 FileOutputStream fileOut = null; 8 9 //コピー元 10 try { 11 fileIn = new FileInputStream(pathFrom); 12 } catch (FileNotFoundException e) { 13 e.printStackTrace(); 14 return bl; 15 } 16 17 //コピー先 18 try { 19 fileOut = new FileOutputStream(pathTo); 20 } catch (FileNotFoundException e) { 21 e.printStackTrace(); 22 return bl; 23 } 24 25 // byte型の配列を宣言 26 byte[] buf = new byte[256]; 27 int len; 28 29 // ファイルの終わりまで読み込む 30 try { 31 while((len = fileIn.read(buf)) != -1){ 32 try { 33 fileOut.write(buf,0,len); 34 } catch (IOException e) { 35 e.printStackTrace(); 36 return bl; 37 } 38 } 39 } catch (IOException e) { 40 e.printStackTrace(); 41 return bl; 42 } 43 44 //ファイルに内容を書き込む 45 try { 46 fileOut.flush(); 47 } catch (IOException e) { 48 e.printStackTrace(); 49 return bl; 50 } 51 52 //ファイルの終了処理 53 try { 54 fileOut.close(); 55 } catch (IOException e) { 56 e.printStackTrace(); 57 return bl; 58 } 59 try { 60 fileIn.close(); 61 } catch (IOException e) { 62 e.printStackTrace(); 63 return bl; 64 } 65 66 return true; 67 }
回答2件
あなたの回答
tips
プレビュー