gpt4 book ai didi

Java 压缩 try/catch 代码异常

转载 作者:行者123 更新时间:2023-11-29 09:49:11 26 4
gpt4 key购买 nike

有什么方法可以压缩 try/catch block 代码吗?现在,我的代码在 try/catch 代码中有一个 try/catch 代码。

if(petType.equals("DOG")) {

try {
String name = input.next();
String owner = input.next();
double weight = input.nextDouble();
SimpleDateFormat stdDate = new SimpleDateFormat("MM/dd/yy");

try {
Date vaccineDate = stdDate.parse(input.next());
boolean fixed = input.nextBoolean();
Dog x = new Dog(name,owner,weight,vaccineDate,fixed);
object.addPet(x);
}
catch (ParseException ex) {
System.out.println("ERROR - Vaccine date " + input.next() + " is not in mm/dd/yy format!");
input.nextLine();
}

}
catch(NoSuchElementException ex) {
System.out.println("ERROR - Missing fields. Skipping line " + lineNumber + "...");
input.nextLine();
}

}

最佳答案

你可以这样做

if(petType.equals("DOG")) {

try {
String name = input.next();
String owner = input.next();
double weight = input.nextDouble();
SimpleDateFormat stdDate = new SimpleDateFormat("MM/dd/yy");
Date vaccineDate = stdDate.parse(input.next());
boolean fixed = input.nextBoolean();
Dog x = new Dog(name,owner,weight,vaccineDate,fixed);
object.addPet(x);
}
catch(NoSuchElementException ex) {
System.out.println("ERROR - Missing fields. Skipping line " + lineNumber + "...");
input.nextLine();
}
catch (ParseException ex) {
System.out.println("ERROR - Vaccine date " + input.next() + " is not in mm/dd/yy format!");
input.nextLine();
}
}

或者使用 Java 7

try {
...
} catch(ParseException | NoSuchElementException ex) {
...
}

如果这就是压缩的意思。

关于Java 压缩 try/catch 代码异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13300887/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com