Reputation: 107
So I need to add a new method to a program, it requires me accessing this zip folder. The first method downloads from a website and returns a File object.
So now in my method, I'm wanting to change this to be a ZipFile object. At the minute I just want to take in the File, create a ZipFile object using that File, then return it.
So everything is fine, but when I create the ZipFile object, it says an unhandled IOException is there. But if I put the try/catch around it I cannot return the ZipFile. So I create it first and then do the try catch but tells me that the ZipFile is not initialised. Any idea on what I'm missing in my thinking here or how I can sort this?
My code looks like;
ZipFile zipTestData;
try {
zipTestData = new ZipFile(testData)
}catch (IOException io)
log.debug(io.toString());
}catch(Exception e) {
log.debug(e.toString());
}
return zipTestData;
Upvotes: 0
Views: 46
Reputation: 12610
You should not 'swallow' an exception. If an exception occurs, you probably should pass it on for the caller to handle. Otherwise, how would the caller know the operation failed?
You may also use the approach you described, if the caller is prepared to handle the result correctly, like so:
ZipFile zipTestData = null;
try {
zipTestData = new ZipFile(testData)
} catch (IOException io)
log.debug(io.toString());
} catch(Exception e) {
log.debug(e.toString());
}
return zipTestData;
This will return null
to the caller instead of a ZipFile
if the zip cannot be created for whatever reason.
Although, in that specific case, you could just as well write
try {
return new ZipFile(testData)
} catch (IOException io)
log.debug(io.toString());
} catch(Exception e) {
log.debug(e.toString());
}
return null;
The reason for the error you get is that local variables are not initialized by default upon declaration. So when you declare a local variable (ZipFile zipTestData;
) it is not assigned any value. Then, if at run time an exception is thrown at new ZipFile(testData)
, the variable will not get assigned and the return
would try to return the value of that unassigned variable. In Java, that's forbidden.
Upvotes: 2
Reputation: 153
probably you should initialize the ZipFile zipTestData = null; Without stacktrace this is what I could figure out
Upvotes: 1