![](/img/trans.png)
[英]How to create own annotation for junit that will skip test if concrete exception was thrown during execution?
[英]Skip execution if exception thrown
我堅持一些非常基本的東西。 在我們的游戲中,我們有一個leveleditor / loader,可以通過URL來獲取關卡。 現在,如果URL指向不存在的文件,則編輯器應拒絕加載該級別並僅停留在當前級別,我只是在與基本代碼苦苦掙扎。
private void loadLevel(URL url) {
Scanner in = null;
try {
in = new Scanner(new BufferedReader(new InputStreamReader(
url.openStream())));
readLine(in);
in.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
本質上,如果拋出FileNotFound
(或任何其他),則readLine(in)
不應繼續進行。 各種NPE(如果有)。
private void loadLevel(URL url) {
Scanner in = null;
try {
in = new Scanner(new BufferedReader(new InputStreamReader(
url.openStream())));
/*if(in!=null){
readLine(in);
in.close();
}*/
readLine(in);
in.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
編輯:@LuiggiMendoza的建議之后。
finally
使用throws
。 讓調用函數處理它。 我還沒有測試過,但是這種想法就是...
private void loadLevel(URL url) throws IOException, FileNotFoundException {
Scanner in = null;
try {
in = new Scanner(new BufferedReader(new InputStreamReader(
url.openStream())));
if (in == null) throw new FileNotFoundException();
readLine(in);
}
finally {
in.close();
}
}
在一個線程的上下文中,如果下面的這一行引發異常,則下一行代碼將不執行。 如果您認為自己的代碼在執行其他操作,則可能是另一個線程在執行此操作/其他一些代碼
in = new Scanner(new BufferedReader(new InputStreamReader(
url.openStream())));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.