Exceptions

Rule 4: Favor the use of standard exceptions

An attribute that distinguishes an expert programmer from a less experienced one is that EXPERTS STRIVE FOR AND USUALLY ACHIEVE a high degree of CODE-REUSE.

Less Exception classes are uncluttred and are readble , A fewer Exception class means less memory footprint and less time spent classes.
Some of the most commonly used expections :
1.IllegalArgumentException : This is generally the exception to throw when the caller passes in an argument whose value is inappropriate.
2.IllegalStateException. : this exception is thrown because of the state of receiving object.
For example, this would be the exception to throw if the caller attempted to use some object before it had been properly initialized.
ARGUABLY , every erroneous method invocation boils-down to either IllegalArgumentException or state.
But, other exceptions are standardly used in place of IllegalArgumentException or state
Example:
a.if user passes null parameter the standard convention is to throw NullPointerException in place of IllegalArgumentException.
b.another one is if the user passes out-of-range index as parameter then use IndexOutOfBoundsException rather than IllegalArgumentException
c.ConcurrentModificationException – when a obect is expected to be used by single thread and found to be accesed concurrently then this exceptoin is thrown.
d.UnsupportedOperationException -rarey used but used to indicate operation not supported .
example:an append-only List implementation would throw this exception if someone tried to delete an element from the list.

Do not reuse Exception, RuntimeException, Throwable, or Error directly. Treat these classes as if they were abstract. You can’t reliably test for these exceptions because they are superclasses of other exceptions that a method may throw.
Also, we can subclass a standard exception if you want to add more detail (Item 75), but remember that EXCEPTIONS ARE SERIALIZABLE (Chapter 12). THAT ALONE is RESAON NOT TO WRITE your OWN EXCPETION CLASS without good reason.
choosing exception to throw can be trickey depending on “occassion of use” because the exceptions and not mutually exclusive.
for example :
we have a class that has card-deck details . and then there is a method that deals with hand-draw and it takes “size” as the argument suppose the caller sends the size to be larger than available cards. you may be tempted to use IllegalArgumentException but rule is to throw IllegalStateException if no argument values would have worked, otherwise throw IllegalArgumentException
TODO: Know meaning of above statement.

Published by

Unknown's avatar

sevanand yadav

software engineer working as web developer having specialization in spring MVC with mysql,hibernate

Leave a comment