Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy not use exceptions as regular flow of control?
    primarykey
    data
    text
    <p>To avoid all standard-answers I could have Googled on, I will provide an example you all can attack at will.</p> <p>C# and Java (and too many others) have with plenty of types some of ‘overflow’ behaviour I don’t like at all (e.g <code>type.MaxValue + type.SmallestValue == type.MinValue</code> for example : <code>int.MaxValue + 1 == int.MinValue</code>).</p> <p>But, seen my vicious nature, I’ll add some insult to this injury by expanding this behaviour to, let’s say an Overridden <code>DateTime</code> type. (I know <code>DateTime</code> is sealed in .NET, but for the sake of this example, I’m using a pseudo language that is exactly like C#, except for the fact that DateTime isn’t sealed).</p> <p>The overridden <code>Add</code> method: </p> <pre class="lang-cs prettyprint-override"><code>/// &lt;summary&gt; /// Increments this date with a timespan, but loops when /// the maximum value for datetime is exceeded. /// &lt;/summary&gt; /// &lt;param name="ts"&gt;The timespan to (try to) add&lt;/param&gt; /// &lt;returns&gt;The Date, incremented with the given timespan. /// If DateTime.MaxValue is exceeded, the sum wil 'overflow' and /// continue from DateTime.MinValue. /// &lt;/returns&gt; public DateTime override Add(TimeSpan ts) { try { return base.Add(ts); } catch (ArgumentOutOfRangeException nb) { // calculate how much the MaxValue is exceeded // regular program flow TimeSpan saldo = ts - (base.MaxValue - this); return DateTime.MinValue.Add(saldo) } catch(Exception anyOther) { // 'real' exception handling. } } </code></pre> <p>Of course an if could solve this just as easy, but the fact remains that I just fail to see why you couldn’t use exceptions (logically that is, I can see that when performance is an issue that in certain cases exceptions should be avoided).</p> <p>I think in many cases they are more clear than if-structures and don’t break any contract the method is making.</p> <p>IMHO the “Never use them for regular program flow” reaction everybody seems to have is not that well underbuild as the strength of that reaction can justify.</p> <p>Or am I mistaken?</p> <p>I've read other posts, dealing with all kind of special cases, but my point is there's nothing wrong with it if you are both:</p> <ol> <li>Clear</li> <li>Honour the contract of your method</li> </ol> <p>Shoot me.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    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