gpt4 book ai didi

java - 这在构造函数内安全还是应该移到其他地方

转载 作者:行者123 更新时间:2023-12-01 16:40:13 24 4
gpt4 key购买 nike

我不确定我的代码在构造函数内部发生错误时是否安全,会发生什么?我应该改变编写代码的方式还是就可以了?

构造函数抛出 null 异常或执行失败的新 obj 会发生什么情况?

private Response _response = Response.NONE;
private long _time = System.currentTimeMillis();

public Request(final Site site)
{
final Holder holder = Holder.getInstance().getHolder(site);

if (holder == null)
{
throw new NullPointerException("Failed to find holder");
}

HttpURLConnection connection = null;

try
{
final URL url = new URL(site.toString());

connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "");
connection.connect();

final String streamResponse = new BufferedReader(new InputStreamReader(connection.getInputStream())).lines().collect(Collectors.joining("\n"));

switch (site)
{
case X:
_response = Response.SUCCESS;
_time = <some code here>
break;
}
}
catch (final IOException e)
{

}
finally
{
if (connection != null)
{
connection.disconnect();
}
}
}

public Response getResponse()
{
return _response;
}

public long getTime()
{
return _time;
}

最佳答案

这取决于您正在谈论的构造函数。目前,如果出现错误,只有发生在 try/catch 语句中时才会被捕获。即使如此,您还没有实现 catch 语句来处理错误,因此如果 try/catch 中出现错误,则在当前状态下不会发生任何事情。您可以添加控制台日志来打印错误;但是,这取决于您处理错误的总体方法。

如果您想要在捕获错误方面更灵活一些,您可以让构造函数抛出错误并像这样:

public Request(final Site site) throws NullPointerException, IOException, ..//any other errors

如果您在方法中遇到任何其他类型的错误,您可以将其添加到方法签名中。如果这样做,您仍然需要处理错误,但不是在此处的方法中处理它,而是在调用 Request 构造函数的位置处理它。

所以最终,这取决于您想要如何处理错误以及您想要在哪里处理它。

关于java - 这在构造函数内安全还是应该移到其他地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61872801/

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