Android(java) 개발 코드 리뷰 팁 하나
울 회사의 어떤분이 정리한 자료를 참조하여 요약 정리
=========================================================
Step #1
--------------
FileInputStream fin = null;
try {
fin = new FileInputStream("testfile");
fin.read()...
fin.close(); // 뭐가 문제?
} catch(IOException e) {
e.printStackTrace();
}
=========================================================
Step #2
--------------
FileInputStream fin = null;
try {
fin = new FileInputStream("testfile");
fin.read()...
} catch(IOException e) {
e.printStackTrace();
}finally {
fin.close(); // finally를 통해 어떤 상황에서도 호출 보장
}
=========================================================
Step #3
--------------
FileInputStream fin1 = null, fin2 = null;
try {
fin1 = new FileInputStream("testfile");
fin1.read()...
fin2 = new FileInputStream("testfile2"); // FileNotFoundException
fin2.read()...
} catch(IOException e) {
e.printStackTrace();
}finally {
fin1.close(); // NullPointerException
fin2.close(); // 호출되지 않음
}
=========================================================
Step #4
--------------
FileInputStream fin1 = null, fin2 = null;
try {
fin1 = new FileInputStream("testfile");
fin1.read()...
fin2 = new FileInputStream("testfile2");
fin2.read()...
} catch(IOException e) {
e.printStackTrace();
}finally {
try { fin2.close(); } catch (Exception e) {} // 예외가 발생해도 fin.close() 호출 보장
try { fin1.close(); } catch (Exception e) {}
}
=========================================================
Step #5
--------------
FileInputStream fin1 = null, fin2 = null;
try {
fin1 = new FileInputStream("testfile");
fin1.read()...
fin2 = new FileInputStream("testfile2");
fin2.read()...
} catch(IOException e) {
e.printStackTrace();
}finally {
if (fin2 != null) try { fin2.close(); } catch (Exception e) {} // Null check
if (fin1 != null) try { fin1.close(); } catch (Exception e) {} // Null check
}
=========================================================
Step #6
--------------
FileInputStream fin1 = null, fin2 = null;
try {
fin1 = new FileInputStream("testfile");
fin1.read()...
fin2 = new FileInputStream("testfile2");
fin2.read()...
} catch(IOException e) {
// e.printStackTrace(); // 로그 확인이 어려움
Log.e(TAG, Log.getStackTraceString(e)); // or Log.e(TAG, "error: " + e);
}finally {
if (fin2 != null) try { fin2.close(); } catch (Exception e) {} // Null check
if (fin1 != null) try { fin1.close(); } catch (Exception e) {} // Null check
}
=========================================================
댓글
댓글 쓰기