Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

catch a exception with specific message

Is there a better way for catching specific Exception with a message then doing this:

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

For example the HttpStatusException gives me the Method getStatusCode() where i can easily compare if the error status was 404 or 502 and the can decide what to do:

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;
   }
}

Most other Exceptions dont give me prober Methods, just the Message.

So my question is, is it the right way to do it? With String compares? Or is there a better way?

like image 614
reox Avatar asked Oct 05 '22 10:10

reox


1 Answers

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.

like image 179
Nikhil Agrawal Avatar answered Oct 10 '22 23:10

Nikhil Agrawal