In one of my Java application's code, I have a try-catch-finally
block in which the try
block creates some input and output streams and if something goes wrong I close any earlier opened streams in finally
.
finally
{
if(inputStream != null)
inputStream.close();
if(outputStream != null)
outputStream.close();
}
But the <stream>.close()
line in Eclipse shows error that "Unhandled exception IOException" in the code for this line and shows that the solution is to include another try/catch
in the finally
block which would seem to be bad as a programming practice and I don't want in finally block.
My question is: is it possible to remove this error in Eclipse and use try/catch
only when I need it instead of eclipse telling me to do the try/catch
add. (Since I am already trying to avoid exception by replacing try/catch
with if/else
as possible).
This is not an Eclipse error, it is a Java compiler error. Eclipse is merely reporting the Java compilation error for you. There is no way to "turn it off" as the code does not compile without the try/catch clause. It is a safety feature in Java that forces you to handle commonly thrown Exceptions.
Methods have Exceptions in their signature. For example, InputStream.close() throws an IOException, forcing you to handle it in a try/catch block.
public void close() throws IOException {
...
Throwing an Exception is a way of telling the program that a significant problem - that must be handled - has occurred.
My question is: is it possible to remove this error in eclipse and use try/catch when I need it otherwise not instead of eclipse telling me to do try/catch add.
No, it is not possible.
(Since I am already trying to avoid exception by replacing try/catch with if/else as possible).
You should generally never try to replace try/catch
blocks with if/else
blocks. They are two distinct features with distinct purposes.
Exceptions are an essential Java feature. Read about it and understand it.
Properly this should be done something like this to ensure that we attempt to close both streams.
finally
{
try {
if(inputStream != null)
inputStream.close();
}
catch(Exception e)
{ /* Ignore */ }
try {
if(outputStream != null)
outputStream.close();
}
catch(Exception e)
{ /* Ignore */ }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With