我不确定在构造函数内部发生错误时我的代码是否安全?
我应该更改编写代码的方式还是很好?

构造函数引发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/

10-12 00:19
查看更多