Boring series - teach you how to correctly handle exceptions

At work, often encounter situations of chaos Exception handling:

  1. Either swallow exceptions, do not print any log;
  2. When either logging, log level is wrong, or to kill important error stack information, doing production troubleshooting, simply makes you go crazy.

I have this blog, is also a record of open source components, abnormal K out on their own, cause I spent a long time troubleshooting - https://www.cnblogs.com/chongsha/p/11931109.html

Here we use a piece of code 1 taken as an example, the code is casual search of the Internet, the original author do not take offense.

1   / * 
2     * encryption
 3     * 1. configured key generator
 4     * The rules ecnodeRules initialization key generator
 5     * 3. Generate Key
 6     * 4. Create and initialize the scrambler
 7     * The content encryption
 8     * 6. return the string
 . 9     * / 
10      public  static string AESEncode (encodeRules string, string Content) {
 . 11          the try {
 12 is              // 1. configured key generator, designated as AES algorithm insensitive 
13 is              the KeyGenerator keygen = the KeyGenerator .getInstance ( "the AES" );
 14              // 2. the rules ecnodeRules initialization key generator
 15              // generates a 128-bit random source, based on the incoming byte array 
16             keygen.init (128, new new a SecureRandom (encodeRules.getBytes ()));
 . 17                // 3. symmetric key to generate the original 
18 is              a SecretKey original_key = keygen.generateKey ();
 . 19                // 4. symmetric key to obtain the original byte array 
20 is              byte [] RAW = original_key.getEncoded ();
 21 is              // 5. The byte array is generated according to an AES key 
22 is              a SecretKey key = new new SecretKeySpec (RAW, "AES" );
 23 is                // 6. The AES algorithm specified from into encryption module 
24              the cipher cipher = Cipher.getInstance ( "the AES" );
 25                //7. The scrambler initialization, the first parameter is encrypted (ENCRYPT_MODE) or decrypted decryption (DECRYPT_MODE) operation, the second parameter used for the KEY 
26 is              cipher.init (Cipher.ENCRYPT_MODE, Key);
 27              // 8. The acquired encryption content byte array (set here to utf-8) otherwise, if the contents of the mixing Chinese and English will be decrypted into Chinese distortion 
28              byte [] = content.getBytes byte_encode ( "UTF-. 8" );
 29              // . 9 according initialized Encryptor - encryption: the data encryption 
30              byte [] = byte_AES Cipher.doFinal (byte_encode);
 31 is            // 10. the encrypted data is converted to a string of
 32              // herein will find use Base64Encoder less than a pack
 33              // solution:
 34              // in the Build path of the project to remove the JRE System library, and then add the library JRE System library, recompile after all normal. 
35             String AES_encode=new String(new BASE64Encoder().encode(byte_AES));
36           //11.将字符串返回
37             return AES_encode;
38         } catch (NoSuchAlgorithmException e) {
39             e.printStackTrace();
40         } catch (NoSuchPaddingException e) {
41             e.printStackTrace();
42         } catch (InvalidKeyException e) {
43             e.printStackTrace();
44         } catch (IllegalBlockSizeException e) {
45             e.printStackTrace ();
 46 is          } the catch (BadPaddingException E) {
 47              e.printStackTrace ();
 48          } the catch (UnsupportedEncodingException E) {
 49              e.printStackTrace ();
 50          }
 51 is          
52 is          // If there are mistakes, Returning nulll 
53 is          return  null ;         
 54 is      }

The main problem is that sections of the code:

  1. We ate an exception, because it is a public class, not even logging
  2. After an exception, still returns a null value.

This method is when we usually use, if you do not read the source code directly, the first instinct is to return the correct result, if incorrect, it will throw an exception. However, this code has returned null, the user experience will be crazy, this is what ah, why not, obviously there is no error, desperation, a look into the code. . . The original is to get rid of the abnormal.

This code is to make recommendations for improvement are:

  1. Statement throws in approach is
  2. If you feel uncomfortable 1 program, direct a big catch Exception, and then throw new RuntimeException (e.getMessage (), e);
  3. Wrong is wrong, the error can not kill myself, and then returns a null.

When either logging, log level is wrong, or to kill important error stack information, doing production troubleshooting, simply makes you go crazy.

When using log4j logging, use the correct logger.error () for logging, please pay attention to override this method, do not use the Exception getMessage () method only records the message for this exception, and the exception to the error stack to abandon, unusual error stack is useful information, it will tell you which lines of code in the wrong, so you can quickly locate the error.

 1 package com.demo;
 2 
 3 public class Test {
 4 
 5     public static void main(String[] args) {
 6         try {
 7             int a = 0;
 8             int b = 1;
 9 
10             System.out.println(b / a);
11         } catch (Exception e) {
12             e.printStackTrace();
13         }
14     }
15 
16 }

 

This code error stack information:

java.lang.ArithmeticException: / by zero
at com.demo.Test.main(Test.java:10)

This line error message at com.demo.Test.main (Test.java:10) marked the wrong location, you can quickly locate at any place. So when logging in, please do not get rid of the error message stack.

 

Guess you like

Origin www.cnblogs.com/chongsha/p/12657724.html