Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Firstly, it sounds like you may be using try/catch too often - particularly if you're catching <code>Exception</code>. try/catch blocks should be relatively rare; unless you can really "handle" the exception, you should just let it bubble up to the next layer of the stack.</p> <p>Now, assuming you really <em>do</em> want all of these try/catch blocks, why is it not an option to create a delegate? With anonymous methods and lambda expressions, as well as the Func/Action delegates in the <code>System</code> namespace, there's basically very little work to do. You write:</p> <pre><code>public void SurroundWithTryCatch(Action action) { try { action(); } catch(Exception ex) { //something even more boring stuff } } </code></pre> <p>and then your <code>SurroundWithTryCatch(MyMethod)</code> will work fine, if it takes no paramaters.</p> <p>Alternatively, if you don't want to call a <em>different</em> method, just write:</p> <pre><code>public void MyMethod() { SurroundWithTryCatch(() =&gt; { // Logic here }); } </code></pre> <p>If you need to return from the method, you can do:</p> <pre><code>public int MyMethod() { return SurroundWithTryCatch(() =&gt; { // Logic here return 5; }); } </code></pre> <p>with a generic overload of <code>SurroundWithTryCatch</code> like this:</p> <pre><code>public T SurroundWithTryCatch&lt;T&gt;(Func&lt;T&gt; func) { try { return func(); } catch(Exception ex) { //something even more boring stuff } } </code></pre> <p>Most of this would be fine in C# 2 as well, but type inference won't help you quite as much and you'll have to use anonymous methods instead of lambda expressions.</p> <p>To go back to the start though: try to use try/catch less often. (try/finally should be much more frequent, although usually written as a using statement.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload