Concise C# Part 2 : Try Catch and reusability

Posted on : 03-09-2009 | By : manitra | In : C#

0

Exception handling is an important part of any software. In this post, I will talk about a trick to make but some kind of reusability on exception handling.

This post is part of a serie about making C# code shorter

When you write code, you usually try to reuse your code by creating methods and calling those methods each time you the need their functionality. When working with exceptions, it’s a bit tricky because, they don’t follow the normal code flow, they jump out of your method … unless you catch them. The consequence is that you usually have multiple similar try {} catch {} blocks that are often copied and pasted.

This is what usually happens

  1. public void Method1()
  2. {
  3.     try
  4.     {
  5.         //method 1 content
  6.     }
  7.     catch (ThreadAbortException)
  8.     {
  9.     }
  10.     catch (IOException ex)
  11.     {
  12.         //IO exception handling
  13.     }
  14.     finally
  15.     {
  16.         //add any code for releasing ressource
  17.     }
  18. }
  19.  
  20. public void Method2()
  21. {
  22.     try
  23.     {
  24.         //method 2 content
  25.     }
  26.     catch (ThreadAbortException)
  27.     {
  28.     }
  29.     catch (IOException ex)
  30.     {
  31.         //IO exception handling
  32.     }
  33.     finally
  34.     {
  35.         //add any code for releasing ressource
  36.     }
  37. }

The solution to reuse the exception block

This is what you could do to reuse the same error handling code block in c# :

  1. public void Method1()
  2. {
  3.     Do(() =>
  4.     {
  5.         //method 1 content
  6.     });
  7. }
  8.  
  9. public void Method2()
  10. {
  11.     Do(() =>
  12.     {
  13.         //method 2 content
  14.     });
  15. }
  16.  
  17. protected void Do(Action method)
  18. {
  19.     try
  20.     {
  21.         //code to call before each methods
  22.         method();
  23.         //code to call after each methods success
  24.     }
  25.     catch (ThreadAbortException)
  26.     {
  27.     }
  28.     catch (IOException ex)
  29.     {
  30.         //IO exception handling
  31.     }
  32.     finally
  33.     {
  34.         //add any code for releasing ressource
  35.     }
  36. }
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Netvibes
  • Technorati
  • TwitThis

Write a comment