简体   繁体   中英

Is it a good practice/ non-expensive to call a method that doesn't throw exception inside try block in Java?

for eg currently, I have this implementation:

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try
        {
           //write to bos
        } 
        catch (Exception exception)
        {
            throw new exception
        }

       somemethod(bos, foo1, foo2);
    }

Is it a good/bad practice/ inexpensive/expensive or makes any difference if I change this method to following:

        try(ByteArrayOutputStream bos = new ByteArrayOutputStream())
        {
           //write to bos
           somemethod(bos, foo1, foo2);
        } 
        catch (Exception exception)
        {
            throw new exception
        }

      }

Had to move some method inside try as it needs bos variable.

Performance wise? Doesn't matter in the slightest.

Code-style-wise: That's a different story. You shouldn't toss methods into a try block unless the associated catch and/or finally block are designed to deal with it. Instead, do this:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
    // write to bos
} catch (Exception e) {
   // handle things - you really want to catch ALL exceptions?
}
somemethod(bos, foo1, foo2);

ie move the declaration outside. You can even do something like:

String foo; // no value assigned yet
try (someResource) {
   foo = readFromIt; // assigned here though.
} catch (IOException e) {
   throw new ResourceRetrievalException(e);
}
System.out.println(foo); // hey I'm using foo, outside the try!

NB: BAOS does not need a try block. If your linter is complaining about it, get a better linter. BAOS is not actually a resource that needs closing, the garbage collector will do the job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM