Monday, February 19, 2018

Throw exceptions


https://www.cnblogs.com/shihuc/p/5201905.html
http://blog.csdn.net/qq_14982047/article/details/50989761


这里写图片描述


Checked vs unchecked

Error happens in JVM
Checked Exception: checked during compiling time

                 +-----------+
                 | Throwable |
                 +-----------+
                  /         \
                 /           \
          +-------+          +-----------+
          | Error |          | Exception |
          +-------+          +-----------+
           /  |  \           / | \        \
          \________/       \______/         \
                                        +------------------+
          unchecked        checked      | RuntimeException |
                                        +------------------+
                                         /   |    |      \
                                        \_________________/
                        
                                            unchecked

Exceptions in Constructor:
https://stackoverflow.com/questions/6086334/is-it-good-practice-to-make-the-constructor-throw-an-exception

Throwing exceptions in a constructor is not bad practice. In fact, it is the only reasonable way for a constructor to indicate that there is a problem; e.g. that the parameters are invalid.
However explicitly declaring or throwing java.lang.Exception is almost always bad practice.
You should pick an exception class that matches the exceptional condition that has occurred. If you throw Exception it is difficult for the caller to separate this exception from any number of other possible declared and undeclared exceptions. This makes error recovery difficult, and if the caller chooses to propagate the Exception, the problem just spreads.

Someone suggested using assert for checking arguments. The problem with this is that checking of assert assertions can be turned on and off via a JVM command-line setting. Using assertions to check internal invariants is OK, but using them to implement argument checking that is specified in your javadoc is not a good idea ... because it means your method will only strictly implement the specification when assertion checking is enabled.
The second problem with assert is that if an assertion fails, then AssertionError will be thrown, and received wisdom is that it is a bad idea to attempt to catch Error and any of its subtypes.

No comments:

Post a Comment

java special for collection size, array size, and string size

Size: For Collections (eg: Map, List, etc ): usually it use collection.size(), eg         Map<Character, Integer> map ...