How to handle exceptions when instantiating class objects
java version "1.7.0_45"
java version "1.7.0_45"
Hello
I'm initializing class methods in the constructor However, the new URL (uploadurl) will throw an exception in the constructor Therefore, if this happens, the user should not be able to continue Since the constructor cannot return anything, I wonder if this is the best way to deal with this problem?
Thank you very much for any suggestions,
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); } }
Solution
Typically, allow exceptions to be propagated directly to the caller or wrapped in your own higher-level Abstract exceptions (in your case, just make it look more appropriate directly.)
public MultipleFileTransfer(final String uploadUrl) throws MalformedURLException { // -------------------------------------------------^ dataOutputStream = null; fileInputStream = null; httpURLConnection = null; url = new URL(uploadUrl); }
Since your instance is useless without a URL, it makes sense to construct a failure
Or, if you want to record it in the constructor (but if it is propagating, usually any record will be handled by the caller if appropriate):
// 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 } }