gpt4 book ai didi

java - 这是正确的运动方案吗?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:07:13 26 4
gpt4 key购买 nike

Thinking in Java 中有一个练习:

Create a class called FailingConstructor with a constructor that might fail partway through the construction process and throw an exception. In main(), write code that properly guards against this failure.

这是我的解决方案:

class E1 extends Exception {
private FailingConstructor f;
E1(FailingConstructor f) { this.f = f; }
FailingConstructor getF() { return f; }
}

class FailingConstructor {
private Integer value;
FailingConstructor(int i) throws E1 {
if (i < 0) throw new E1(this);
value = i;
}
void set(int value) { this.value = value; }
public String toString() { return value.toString(); }
}

public class Program {
public static void main(String[] args) {
try {
FailingConstructor f2 = new FailingConstructor(-11);
} catch (E1 e) {
e.getF().set(0);
System.out.println(e.getF());
}
}
}

你能告诉我,这是正确的运动方案吗?我找到的解决方案 ( here) 看起来很奇怪且不合逻辑,我认为我的解决方案比这个更好。

最佳答案

将半构造实例的引用传递给异常的构造函数对我来说似乎是个坏主意。

并且在 catch 子句中改变该实例没有任何意义,因为在执行 catch 子句之后,您的代码无论如何都不会引用该实例。

catch 子句应该报告异常发生(打印错误消息或堆栈跟踪),如果适用则抛出不同的异常,或者 - 如果适本地防止这种失败意味着成功创建必须确保实例 - 创建 FailingConstructor 的新实例,保证其创建不会引发异常。如果您选择最后一种方法,您应该在 try block 之前声明 FailingConstructor 变量,以便它保留在 try-catch block 之后的范围内。

public class Program {
public static void main(String[] args) {
FailingConstructor f2 = null;
try {
f2 = new FailingConstructor(-11);
} catch (E1 e) {
f2 = new FailingConstructor(); // one way to recover from the exception
// is to use a different constructor
// that doesn't throw an exception
}
// now you can access f2
}
}

关于java - 这是正确的运动方案吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38608517/

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