今天在水木上看到一篇文章,原来自己那么多年写的代码都是如此的圡。

public class T{
     // 这里编译时是会报错的:unreported exception
     private String s = intS();
     private String initS() throws Exception{
          return "www.codigg.com";
     }
}

为了解决这个问题,我通常的做法都是:

public class T{
     private String s;
     {
          try{
               s = initS();
          }catch(Exception e){}
     }
     private String initS() throws Exception{
          return "www.codigg.com";
     }
}

实际上有更优雅的做法,推荐一下:

public class T{
     private String s = initS();
     private T() throws Exception{}
     private String initS() throws Exception{
          return "www.codigg.com";
     }
}