Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If we ignore the scoping-block issue for a moment, the complier would have to work a lot harder in a situation that's not well defined. While this is not impossible, the scoping error also forces you, the author of the code, to realise the implication of the code you write (that the string s may be null in the catch block). If your code was legal, in the case of an OutOfMemory exception, s isn't even guaranteed to be allocated a memory slot: </p> <pre><code>// won't compile! try { VeryLargeArray v = new VeryLargeArray(TOO_BIG_CONSTANT); // throws OutOfMemoryException string s = "Help"; } catch { Console.WriteLine(s); // whoops! } </code></pre> <p>The CLR (and therefore compiler) also force you to initialize variables before they are used. In the catch block presented it can't guarantee this. </p> <p>So we end up with the compiler having to do a lot of work, which in practice doesn't provide much benefit and would probably confuse people and lead them to ask why try/catch works differently. </p> <p>In addition to consistency, by not allowing anything fancy and adhering to the already established scoping semantics used throughout the language, the compiler and CLR are able to provide a greater guarantee of the state of a variable inside a catch block. That it exists and has been initialized.</p> <p>Note that the language designers have done a good job with other constructs like <em>using</em> and <em>lock</em> where the problem and scope is well defined, which allows you to write clearer code.</p> <p>e.g. the <em>using</em> keyword with <em>IDisposable</em> objects in:</p> <pre><code>using(Writer writer = new Writer()) { writer.Write("Hello"); } </code></pre> <p>is equivalent to:</p> <pre><code>Writer writer = new Writer(); try { writer.Write("Hello"); } finally { if( writer != null) { ((IDisposable)writer).Dispose(); } } </code></pre> <p>If your try/catch/finally is hard to understand, try refactoring or introducing another layer of indirection with an intermediate class that encapsulates the semantics of what you are trying to accomplish. Without seeing real code, it's hard to be more specific.</p>
 

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