我正在自动化登录应用程序,点击相应页面并注销的情节。
在这里如何估计需要使用try catch的时间和地点?
答案 0 :(得分:0)
这取决于具体情况。
1)对于你想要处理错误的情况(例如,' FileOutputStream'将抛出' FileNotFoundException'
try{FileOutputStream out = new FileOutputStream(
new File(System.getProperty("user.dir") + "\\needful\\output.xlsx"));
workbook.write(out);
workbook.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
2)即使某些功能失败,您希望代码在哪里运行。 (例如,验证和断言)
Assert.assertEquals(21, 25); //here the code execution stops
//here the code fails yet the script will continue its execution.
try{
Assert.assertEquals(21, 25);
}catch(Exception e){
e.printStackTrace();
}
3)如果你想添加' finally {}'函数使得"即使从try或catch块中抛出异常,也始终会执行finally子句中的代码。" - Link
public void open_File(){
FileReader reader = null;
try {
reader = new FileReader("file\path\");
//do something here
} catch (IOException e) {
//do something clever with the exception
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
//do something clever with the exception
}
}
System.out.println("--- File Process Ended ---");
}
}