Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eclipse asks me to surround with try/catch in finally block - possible to disable it?

Tags:

java

eclipse

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).

like image 469
Ashutosh Avatar asked Nov 29 '22 16:11

Ashutosh


2 Answers

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.

like image 149
Charles Goodwin Avatar answered Dec 09 '22 09:12

Charles Goodwin


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 */ }
}
like image 35
Paweł Obrok Avatar answered Dec 09 '22 09:12

Paweł Obrok