a) It is bad practice to place the complete code inside a try block.
- a1) In addition to catching exceptions, try-block is documentation in which an exception can occur. So put it close to the point, you mean.
- a2) In bad circumstances, you have a file to read and add it later for writing, but your exception (FileNotFoundException) was only written at a glance. The hard volume around problem areas will help you identify further problems.
b) Do not catch the basic exception for completeness or avoid multiple catch blocks. If you want to write to a file, many things can go wrong: There is no permission, an illegal file name, there is no space on the device .... If you present a general message to the user ("Could not write file" + name), he does not know , what to do. Be very specific, and you can tell him: "Only 20 MB left on the device" + devicename + "We need another 8 MB (28 MB in total), please free your space and try again or select another device!" ), If you catch the โExceptionโ, the chances are high that you think of some exception, but another happens and is not handled correctly, because the catch block was not written with this in mind. The best chance of finding this exception is to let it pop up or record it if the logs are monitored regularly.
This may be the difference between developing an application that is simply used by end users, or developing an API that is used by other developers. In the API, you often want to wrap an exception in your own exception to make it easier to work with your api, and if you have a single way to handle exceptions. If your code can throw a lot of exceptions and lead to an ugly client code where your client will have to specify a bunch of exceptions again and again, you often end the exceptions and reverse them:
try { ... } catch {FileNotFoundException fnfe} { throw new MyApiException (fnfe); } catch {PermissionDeniedException pde} { throw new MyApiException (pde); } catch {IOException ioe} { throw new MyApiException (ioe); }
This way, your client can decide how to handle the exception, and find the specific type of exception, if interested, inside your exception.
As Landei points out, in Java 7 there will be a simplified method to catch a few exceptions, but not just with a common superclass, see this link here
source share