.Net

Sharing the code between multiple exceptions

Today I had a situation where I wanted to do same opertation in case of different exceptions. I came up with something simple

Here is the situation:

try{
  // Exception throwing code
}catch(MongoConnectionException ex){
  // Some code here
}catch(IOException ex){
  // Some code here
}catch(SocketException ex){
  // Some code here
}

Now this looks already quite ugly. Not for you? Ok then its ugly for me 🙂

So what I did some may consider it even more ugly but I can atleast share the code

I did it so that

try{
  // Exception throwing code
}catch(Exception ex){
  if(ex is MongoConnectionException || ex is IOException || ex is SocketConnection){
    // Do some specific logic or setting of state for these type of exceptions
}
  // Do some common logic here
}

If you find some problem in doing this please let me know so that I can fix my code as well 🙂 But this reduced my code.

Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s