如何处理实例化类对象时发生的异常

前端之家收集整理的这篇文章主要介绍了如何处理实例化类对象时发生的异常前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
java version "1.7.0_45"

你好

我正在构造函数中初始化类方法.但是,新URL(uploadUrl)将在构造函数中引发异常.因此,如果发生这种情况,用户应该无法继续.由于构造函数无法返回任何内容,我想知道这是处理此问题的最佳方法吗?

非常感谢任何建议,

public class MultipleFileTransfer {
    private static final String TAG = MultipartUtility.class.getSimpleName();

    private DataOutputStream dataOutputStream;
    private FileInputStream fileInputStream;
    private HttpURLConnection httpURLConnection;
    private URL url;

    public MultipleFileTransfer(final String uploadUrl) {
        dataOutputStream = null;
        fileInputStream = null;
        httpURLConnection = null;

        try {
            url = new URL(uploadUrl);
        } catch (MalformedURLException e) {
            Log.wtf(TAG,e.getMessage()); /* <-- How to handle a failure */
        }
    }

    /* Factory method that initializes the class methods and returns the class object */
    public static MultipleFileTransfer getInstance(final String uploadUrl) {

        /* Check that a valid url has been entered correctly */
        if(!URLUtil.isValidUrl(uploadUrl)) {
            Log.wtf(TAG,"Invalid url: " + uploadUrl);
            return null;
        }

        return new MultipleFileTransfer(uploadUrl);
    }
}

解决方法

As the constructor cannot return anything,I am wondering that is the best way to handle this?

通常,允许异常直接传播给调用者,或者将其包装在您自己的更高级抽象异常中. (在你的情况下,只是让它直接看起来更合适.)

public MultipleFileTransfer(final String uploadUrl) throws MalformedURLException {
// -------------------------------------------------^
    dataOutputStream = null;
    fileInputStream = null;
    httpURLConnection = null;

    url = new URL(uploadUrl);
}

由于您的实例在没有URL的情况下没用,因此构造失败是有意义的.

或者,如果要在构造函数中记录它(但如果它正在传播,通常任何记录,如果适当的话将由调用者处理):

// Logging and re-throwing,but probably not recommended
public MultipleFileTransfer(final String uploadUrl) throws MalformedURLException {
// -------------------------------------------------^
    dataOutputStream = null;
    fileInputStream = null;
    httpURLConnection = null;

    try {
        url = new URL(uploadUrl);
    } catch (MalformedURLException e) {
        Log.wtf(TAG,e.getMessage());
        throw e;                       // <== Rethrowing
    }
}

猜你在找的Java相关文章