我有一段從文件讀取數據的代碼。我想在此代碼中強制執行IOException以進行測試(我想在此例中檢查代碼是否引發正確的自定義異常)。讀取文件時強制IOException
有沒有什麼辦法可以創建一個文件,防止被讀取,例如?也許處理一些安全檢查可以提供幫助?
請注意,傳遞一個不存在的文件的名字是無濟於事的,因爲FileNotFoundException有一個單獨的catch子句。
這裏是爲了更好地理解問題的一段代碼:
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(csvFile));
String rawLine;
while ((rawLine = reader.readLine()) != null) {
// some work is done here
}
} catch (FileNotFoundException e) {
throw new SomeCustomException();
} catch (IOException e) {
throw new SomeCustomException();
} finally {
// close the input stream
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// ignore
}
}
}
你可以嘗試閱讀,你不能讀取文件。在Linux上'/ proc/kcore'是一個很好的選擇,就像'/ etc/shadow'一樣。 – 2011-07-25 12:21:20
不是一個答案,而是一個觀察。您應該使用您的自定義異常來封裝IOException以保留完整的堆棧跟蹤。即'拋出SomeCusomException(e)' – 2012-10-12 20:51:08