java version "1.7.0_45"
你好
我正在构造函数中初始化类方法。但是,new 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 - 如何处理实例化类对象时出现的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31260123/