Be careful about the risks caused by exceptions (2)

Source: Internet
Author: User

Link:Be careful about the risks caused by exceptions (1)

Do not capture generic exceptionsIn complex software, there are often several different exception methods thrown during execution of specific code blocks. Dynamic Loading of a class and instantiation of an object may produce several different exceptions, including ClassNotFoundException, InstantiationException, IllegalAccessException, and ClassCastException.
In this case, a busy programmer may simply package the method call in a try/catch Block that only captures the Exception of the generic type, instead of adding four different catch blocks to the end of the try block (see the following code listing 3 ). It seems that there is no such thing, but it will produce some unintentional secondary effects. For example, if className () is null, Class. forName () will throw an NullPointerException and be captured in this method. In this case, the catch block will catch this Exception, although it never intended to catch such an Exception, just because NullPointerException is a subclass of RuntimeException and RuntimeException is a subclass of Exception. Therefore, a common catch (Exception e) will capture all RuntimeException subclasses, including NullPointerException, IndexOutOfBoundsException, and ArrayStoreException. Generally, a programmer does not intend to capture these exceptions.
In code listing 3, a null className causes an NullPointerException exception, which indicates that the class name is invalid in the called method.
Code List 3

  1. PublicSomeInterface buildInstance (StringClassName ){
  2. SomeInterface impl =Null;
  3. Try{
  4. ClassClazz =Class. ForName (className );
  5. Impl = (SomeInterface) clazz. newInstance ();
  6. }
  7. Catch(ExceptionE ){
  8. Log. error ("Error creating class:" + className );
  9. }
  10. ReturnImpl;
  11. }

Another result of using the generic capture clause is to limit log records, because catch does not know which special exception is captured. In the face of this problem, some programmers use the method of adding detection to view the exception type (code list 4), which is in line with the purpose of using catch blocks.
Code list 4
  1. Catch(ExceptionE ){
  2. If(EInstanceof ClassNotFoundException){
  3. Log. error ("Invalid class name:" + className + "," + e. toString ());
  4. }
  5. Else{
  6. Log. error ("Cannot create class:" + className + "," + e. toString ());
  7. }
  8. }

Code List 5 provides a complete example of capturing special exceptions, which may be interesting to some programmers. The instanceof operator is not mandatory because this special exception is captured. Each checked exception (ClassNotFoundException, InstantiationException, IllegalAccessException) is captured and processed. If a class is correctly loaded but the SomeInterface interface is not implemented, a ClassCastException exception is generated. This exception is also verified.
Code List 5

  1. PublicSomeInterface buildInstance (StringClassName ){
  2. SomeInterface impl =Null;
  3. Try{
  4. ClassClazz =Class. ForName (className );
  5. Impl = (SomeInterface) clazz. newInstance ();
  6. }
  7. Catch(ClassNotFoundExceptionE ){
  8. Log. error ("Invalid class name:" + className + "," + e. toString ());
  9. }
  10. Catch(InstantiationExceptionE ){
  11. Log. error ("Cannot create class:" + className + "," + e. toString ());
  12. }
  13. Catch(IllegalAccessExceptionE ){
  14. Log. error ("Cannot create class:" + className + "," + e. toString ());
  15. }
  16. Catch(ClassCastExceptionE ){
  17. Log. error ("Invalid class type," + className
  18. + "Does not implement" + SomeInterface.Class. GetName ());
  19. }
  20. ReturnImpl;
  21. }

In some cases, a better way is to throw a known exception (or create a new exception) instead of trying to process it in the current method. This allows the call method to handle this error by placing this exception in a known context.

The following code listing 6 provides a replacement version of The buildInterface () method. If a problem occurs when a class is loaded or instantiated, this version throws a ClassNotFoundException exception. In this example, calling a method ensures a correct instantiated object or an exception. In this way, you do not need to check whether the returned object is empty.
Note that this example uses the Java 1.4 method to create a new exception that has been encapsulated by another exception to save the original stack trace information. Otherwise

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.