Java Reference
In-Depth Information
intensive and could result in a number of exception classes, and their management could be a
problem. he other way is to create a generic exception and describe what caused it. his approach
is more concise, but it makes it diicult to handle the diferent situations. he best approach is to
be somewhere in the middle.
10.4.4 Naming the Exceptions
he names of the exceptions should always be meaningful and must express what caused them.
For example, java.io.IOException has a good name and tells you that there is a problem
with the IO operation. he class java.lang.Exception provides a generic exception class
for all the situations that are not managed by the standard Java APIs. herefore it is a good prac-
tice to avoid using the java.lang.Exception as it is too generic and gives too little infor-
mation about what went wrong. Instead, the developer can create a speciic exception, such as
AccountNumberNotFoundException .
10.4.5 Balancing the Catch
In any try-catch block of code, it is possible that there could be multiple catch scenarios that could
be managed with just one catch block for any error happening in the try block. his is not a good
practice and the best practice under such circumstances would be to include as many catch blocks
as shown below:
try {
...
...
} catch (ClassCastException e1) {
...
} catch (FileNotFoundException e) {
...
} catch (IOException e) {
...
} catch (Exception ex) {
...
}
10.4.6 Using Finally
It must be noted that the inally block in the Java programming code is some code that is executed
anyway if the try block is successful or if an exception was thrown. his part is often ignored by
the application developers, and this will cause a lot of resource-related problems in the executing
system. his is very important when one is dealing with system resources, such as iles or database
connections. If an exception was thrown (and normally you can't really be sure when to expect it),
then it can happen that you may fail to execute some cleanup code and leave resources allocated or
objects in an inconsistent state. he inally block of the code helps to ensure that these resources
are properly closed and the executing environment is left in a healthy state.
Search WWH ::




Custom Search