处理构造函数中捕获的 Java 异常,以及最终成员
2022-09-03 18:26:18
我有一些丑陋的代码,想重构它:
public class UdpTransport extends AbstractLayer<byte[]> {
private final DatagramSocket socket;
private final InetAddress address;
private final int port;
/* boolean dead is provided by superclass */
public UdpTransport(String host, int port) {
this.port = port;
InetAddress tmp_address = null;
try {
tmp_address = InetAddress.getByName(host);
} catch (UnknownHostException e) {
e.printStackTrace();
dead = true;
socket = null;
address = null;
return;
}
address = tmp_address;
DatagramSocket tmp_socket = null;
try {
tmp_socket = new DatagramSocket();
} catch (SocketException e) {
e.printStackTrace();
dead = true;
socket = null;
return;
}
socket = tmp_socket;
}
...
导致丑陋的问题是成员之间的相互作用和捕获的异常。如果可能的话,我想保留这些成员。final
final
我想按如下方式形成代码,但是Java编译器无法分析控制流 - 没有办法第二次分配,因为第一次尝试的赋值必须已经抛出控件才能到达子句。address
catch
public UdpTransport(String host, int port) {
this.port = port;
try {
address = InetAddress.getByName(host);
} catch (UnknownHostException e) {
e.printStackTrace();
dead = true;
address = null; // can only have reached here if exception was thrown
socket = null;
return;
}
...
Error:(27, 13) error: variable address might already have been assigned
有什么建议吗?
附言:我有一个约束,那就是构造函数不会抛出 - 否则这一切都很容易。