我想知道,如果我从一个文件中读取对象的参数,给定这个方法,处理这些异常的最佳方法是什么?我的班级 Auto
有4个参数 model, year, km, price
:
public static Auto read(BufferedReader br) {
String model = br.readLine();
int year = Integer.parseInt(br.readLine());
int km = Integer.parseInt(br.readLine());
double price = Double.parseDouble(br.readLine());
return new Auto(model, an, km, pret);
}
从我的阅读资料和我发现的最佳实践来看,考虑到用户可能会将无效输入写入文件,例如 null
为了 year
或者类似的,我想最好是这样:
public static Auto read(BufferedReader br) throws IOException, NumberFormatException{
String model = br.readLine();
int year = Integer.parseInt(br.readLine());
int km = Integer.parseInt(br.readLine());
double price = Double.parseDouble(br.readLine());
return new Auto(model, an, km, pret);
}
... // in main
try {
...
} catch (IOException e) {
//something
} catch (NumberFormatException e) {
throw new RuntimeException("Parsing to int/double failed, invalid input. Try again.", e);
}
我的方法够好吗?
暂无答案!
目前还没有任何答案,快来回答吧!