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.
Throwing an Exception is a way of telling the program that a significant problem – that must be handled – has occurred.
No, it is not possible.
You should generally never try to replace
try/catchblocks withif/elseblocks. They are two distinct features with distinct purposes.Exceptions are an essential Java feature. Read about it and understand it.