java programming common BUG --- imperfect exception handling

  Such a mistake I have committed before, have seen such wording lot of people! Let me also give an example:
  

  public   void  writeFile(File f)  {
  String content 
= null;
  
try {
   
byte[] b = new byte[1024];
   FileInputStream in 
= new FileInputStream(f);
   in.read(b);
   content 
= new String(b);
  }
 catch (Exception e) {
   System.out.println(e.getMessage());
  }


  
if (content.indexOf("hello"> -1{
   System.out.println(
"yes");
  }
 else {
   System.out.println(
"no");
  }

 }


 The above is a simple method, there is a hidden code bug. I encountered a similar code in the maintenance of the system, similar to the practice BUG hidden
deeper! In the case of the systems business and the code is not very familiar, I recommend the following wording:

 . 1 public void  the writeFile (File F)  {  2   String Content  = null ;  . 3 the try {  . 4 byte [] B  = new new byte [ 1024 ];  . 5    the FileInputStream in  = new new  the FileInputStream (F);  . 6    in.read (B);  . 7    Content  = new new  String (B);  . 8   } the catch  (exception E)  {  . 9    Content = "" ; 10 // If an exception occurs, then, content may be empty    
 
   
     
 

 
 

   
11 // The following operations on the content, there may occur NullPointerException exception 12 is    System.out.println (e.getMessage ()); 13 is   }   

14 // The operation may occur a NullPointerException 15 IF  (content.indexOf ( " Hello " > - . 1 { 16    System.out.println ( " Yes " ); . 17   } the else { 18 is    System.out.println ( " NO " ); . 19   } 20 is  }
  
   

  



 In general exception handling is not recommended for direct system.out.println print out!
 A few suggestions:
 If you can not handle an exception, do not catch it.
  ☆ If you capture an exception, do not casually handle it.
  ☆ Try to catch the exception in the near exception is thrown.
  ☆ catch exceptions where it will be logged, unless you intend to throw it back.
  ☆ according to your exception handling must be more than fine to construct your method.
  ☆ need to use several types of abnormalities are several, especially for application exception.
  The low-level abnormality ☆ packaged into high-level programmers easier to understand the abnormality.
  ☆ Try to complete the data output caused by abnormal
  ☆ try to catch the exception has a specific meaning: for example SqlException, rather than simply capture an Exception


  I hope everyone has to help!

Reference:
http://www.blogjava.net/usherlight/archive/2006/10/23/76782.html

Reproduced in: https: //www.cnblogs.com/boiledwater4tom/archive/2009/12/09/1620484.html

Guess you like

Origin blog.csdn.net/weixin_34392906/article/details/93742928