5

有没有更好的方法来捕获带有消息的特定异常,然后执行以下操作:

try{
   methodThatWillProbablyThrowASocketException();
} catch(SocketException e){
   if(e.getMessage().contains("reset")){
      // the connection was reset
      // will ignore
   } else{
      throw e;
   }
}

例如,如果错误状态是 404 或 502,我可以轻松比较HttpStatusException方法getStatusCode(),并且可以决定要做什么:

try{
   methodThatWillProbablyThrowAHTTPException();
} catch(HttpStatusException e){
   if(e.getStatusCode() == 404){
      // not found, will not continue
   } 
   if else(e.getStatusCode() == 502){
      // server errror, try again
   } else{
      throw e;
   }
}

大多数其他异常不给我探测方法,只是消息。

所以我的问题是,这是正确的方法吗?用字符串比较?或者,还有更好的方法?

4

2 回答 2

2

Just do one thing .

  1. Collect all types of exception that are likely to be occur for your project.
  2. Make a separate class by extending Exception.
  3. Override the getCause() method.

http://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getCause%28%29

public Throwable getCause()

Define codes you want for different exceptions Like null-pointer 101 ,, so on......

The use that class every where . So you have to write exception only once and you can use with as many projects.

After building the class it will be reusable for all your needs

If you getting new conditions, update this class only and all the things will be done

This is a better solution according to me...

This way you can get functionality for which you are looking. you have to make it by yourself.

于 2013-04-11T09:17:05.020 回答
2

依赖代码或状态代码很好,但依赖消息可能会出现问题,因为消息可能会发生变化。

您应该考虑重构和定义多个异常或为不同场景定义代码。

于 2013-04-11T09:08:13.227 回答