<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Huddled Masses &#187; Trap</title>
	<atom:link href="http://huddledmasses.org/tag/trap/feed/" rel="self" type="application/rss+xml" />
	<link>http://huddledmasses.org</link>
	<description>You can do more than breathe for free...</description>
	<lastBuildDate>Sat, 28 Jan 2012 21:37:20 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
<cloud domain='huddledmasses.org' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
		<item>
		<title>Trap [Exception] { &#8220;In PowerShell&#8221; }</title>
		<link>http://huddledmasses.org/trap-exception-in-powershell/</link>
		<comments>http://huddledmasses.org/trap-exception-in-powershell/#comments</comments>
		<pubDate>Sat, 13 Oct 2007 21:18:39 +0000</pubDate>
		<dc:creator>Joel 'Jaykul' Bennett</dc:creator>
				<category><![CDATA[Huddled]]></category>
		<category><![CDATA[ErrorHandling]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Scripting]]></category>
		<category><![CDATA[Trap]]></category>

		<guid isPermaLink="false">http://HuddledMasses.org/trap-exception-in-powershell/</guid>
		<description><![CDATA[Brandon and I have been talking a lot about error handling in #PowerShell (on irc.freenode.net) the last few weeks, going back and forth (and dragging half the other channel participants into the discussion) with examples and counter examples and trying to make sense of how it&#8217;s supposed to work, and how it really does work. [...]]]></description>
			<content:encoded><![CDATA[	<p><a href="http://bsonposh.com/modules/wordpress/index.php">Brandon</a> and I have been talking a lot about error handling in #PowerShell (on irc.freenode.net) the last few weeks, going back and forth (and dragging half the other channel participants into the discussion) with examples and counter examples and trying to make sense of how it&#8217;s supposed to work, and how it really does work.  I&#8217;m sure he&#8217;s about to write about <span class="caps">TRAP</span> from the perspective of a sysadmin, but I thought I&#8217;d throw out this post as a complement to his &#8212; from the perspective of a programmer.</p>

	<p>The biggest problem with error handling in PowerShell is an <a href="http://blogs.msdn.com/powershell/archive/2006/12/29/documenting-trap-and-throw.aspx">almost complete lack of documentation</a>.  Neither the <code>trap</code> statement or the <code>throw</code> statement even have about_ documents in the powershell help system, nor do they have pages on <span class="caps">MSDN</span> (that I can find).  In fact, it&#8217;s so bad that I&#8217;ve been known on the <span class="caps">IRC</span> channel to accuse the PowerShell developers of deliberately not writing documentation so that they and the various MVPs could make some extra cash selling books about PowerShell.  <img src='http://huddledmasses.org/wordpress/wp-includes/' alt=';)' class='wp-smiley' />  Despite that, we&#8217;ve been able by trial and error to deduce how these things work, and hopefully this explanation will help some of you come to a better understanding of how you can use error handling in PowerShell.<span id="more-447"></span></p>

	<h4>Exceptions</h4>

	<p>The first thing you need to understand is the concept of Exceptions in .Net (since PowerShell is .Net, and everything you&#8217;ll be traping is going to be a .Net exception).  This is a huge concept, which <a href="http://msdn2.microsoft.com/en-us/library/5b2yeyab.aspx">fortunately</a> is <a href="http://msdn2.microsoft.com/en-us/library/ms954599.aspx">exceptionally</a> <a href="http://msdn2.microsoft.com/en-us/library/aa289505.aspx">well</a> <a href="http://msdn2.microsoft.com/en-us/library/ms229005.aspx">documented</a> and blogged about, so let me just give brief overview (if you don&#8217;t understand anything in this, please read some of the links).  </p>

	<p>In the .Net framework, when an error occurs inside a method which cannot be recovered from inside the method, it&#8217;s considered an <em>exceptional</em> circumstance. Since the problem can&#8217;t be handled by the method, the exception is <em>raised</em> up to the code which called the method by <a href="http://msdn2.microsoft.com/en-us/library/xhcbs8fz.aspx">throwing</a> an error object derived from <a href="http://msdn2.microsoft.com/en-us/library/system.exception.aspx">System.Exception</a>, which has an error message as well as a stack trace and information about the source of the error.  In general, the caller can <a href="http://msdn2.microsoft.com/en-us/library/xtd0s8kd.aspx">catch</a> the exception and deal with it, or, if it can&#8217;t recover from the error either, it can rethrow it or simply not catch it, allowing it to pass on up to the next caller in the stack.</p>

	<p>There are lots of Exception classes in the .Net Base Class Library, and many more in the PowerShell Management and Automation namespaces and in third party cmdlets which you may be dealing with, but the important thing to know is that they are all derived from System.Exception &#8230; and they usually have an error message and a source and/or stack trace.</p>

	<h4>Throw</h4>

	<p>In .Net, you can only throw exceptions, but in PowerShell, you can throw pretty much anything &#8230; the reason is that when you throw something that is not an Exception, it gets automatically wrapped up into a RuntimeException for you.  So in a powershell script you can <code>throw (ls *.txt)</code> and it will simply convert the output of the command <code>ls *.txt</code> to a string and set it as the <em>Message</em> on a RuntimeException.  Of course, you can also throw actual exceptions like&#8221;  <code>throw (new-object IO.DirectoryNotFoundException)</code>.</p>

	<p>Generally speaking, it&#8217;s a good idea to throw an exception from the <a href="http://msdn2.microsoft.com/en-us/library/zbea8bay.aspx">existing exception hiearchy</a> rather than always relying on RuntimeException, because it will give you (or others who use your scripts) the ability to trap more specific errors.  I could go into this in depth, but it&#8217;s been covered rather comprehensively in <a href="http://msdn2.microsoft.com/en-us/library/ms229007.aspx">the .Net Guidelines</a>, so I&#8217;ll spare you  <img src='http://huddledmasses.org/wordpress/wp-includes/' alt=';-)' class='wp-smiley' /> .</p>

	<h4>Trap</h4>

	<p>The first thing you need to know about trapping is that you don&#8217;t always have to do it.  The <code>$ErrorActionPreference</code> can be set to &#8220;Continue&#8221; when an error is thrown (or even &#8220;SilentlyContinue&#8221;) which is basically the equivalent of VB&#8217;s <code>ON ERROR RESUME NEXT</code> and doesn&#8217;t require any specific error handling code.  If you&#8217;re sure of where errors <em>might</em> occur, you can set that to SilentlyContinue at the top of your script, and then after any line where you might have an exception, just check for an error like this: <code>if(-not $?) { #handle $Error ...</code> The <a href="http://bsonposh.com/archives/241">$Error Object</a> is fairly well documented, so I&#8217;ll just leave the rest to your experimentation.</p>

	<p>Note that you can control how much information is shown about each exception with several built-in variables:</p>

	<p><dl><dt>$ReportErrorShowExceptionClass</dt><dd>If true, the class name of exceptions will be output when they are displayed. <strong>Default is false</strong>.</dd>
<dt>$ReportErrorShowInnerException</dt><dd>If true, the full chain of inner exceptions will be output.  Each exception message will be indented an additional level, and formatted by the rest of the options listed here. <strong>Default is false</strong>.</dd>
<dt>$ReportErrorShowSource</dt><dd>If true, the assembly name for the source of the exception will be displayed. <strong>Default is true</strong>.</dd>
<dt>$ReportErrorShowStackTrace</dt><dd>If true, the stack trace of the exception will be output. <strong>Default is false</strong>.</dd>
</dl></p>

	<p>Having said all of that, PowerShell&#8217;s error handling is basically like VB&#8217;s: <code>ON ERROR GOTO TRAP ... RESUME NEXT</code>.  You put a trap in (for each exception you want to handle) and when an exception is thrown, execution goes to the trap&#8217;s scriptblock.  In your trap scriptblock you can try to correct the error and then either <code>continue</code> or <code>break</code>. Ok, it&#8217;s time for an example (followed by the output):</p>

	<div class="posh code posh" style="font-family:monospace;"><br />
<span style="color: #666699; font-weight: bold;">Function</span> <span style="color: #0066cc; font-style: italic;">Test-<span style="font-style: normal;">Trap1</span></span><span style="color: #333;">&#40;</span><span style="color: #333;">&#41;</span> <span style="color: #333;">&#123;</span><br />
&nbsp; &nbsp;<span style="color: #666699; font-weight: bold;">trap</span> <span style="color: #003366; font-weight: bold;"><span style="color: #333;">&#91;</span>Exception<span style="color: #333;">&#93;</span></span> <span style="color: #333;">&#123;</span> <br />
&nbsp; &nbsp; &nbsp; <span style="color: #0066cc; font-style: italic;">write-<span style="font-style: normal;">host</span></span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #0066cc; font-style: italic;">write-<span style="font-style: normal;">error</span></span> $<span style="color: #333;">&#40;</span><span style="color: #009900;">&quot;TRAPPED: &quot;</span> <span style="color: #66cc66;">+</span> <span style="color: #660033; font-weight: bold;">$_</span>.<span style="color: #003366;">Exception</span>.<span style="color: #003366;">GetType</span><span style="color: #333;">&#40;</span><span style="color: #333;">&#41;</span>.<span style="color: #003366;">FullName</span><span style="color: #333;">&#41;</span>; <br />
&nbsp; &nbsp; &nbsp; <span style="color: #0066cc; font-style: italic;">write-<span style="font-style: normal;">error</span></span> $<span style="color: #333;">&#40;</span><span style="color: #009900;">&quot;TRAPPED: &quot;</span> <span style="color: #66cc66;">+</span> <span style="color: #660033; font-weight: bold;">$_</span>.<span style="color: #003366;">Exception</span>.<span style="color: #003366;">Message</span><span style="color: #333;">&#41;</span>; <br />
&nbsp; &nbsp; &nbsp; <span style="color: #666699; font-weight: bold;">continue</span>; <br />
&nbsp; &nbsp;<span style="color: #333;">&#125;</span><br />
&nbsp; &nbsp;<span style="color: #0066cc; font-style: italic;">write-<span style="font-style: normal;">host</span></span> <span style="color: #009900;">&quot;Hello &quot;</span> <span style="color: #000066;">-nonewline</span>; <br />
&nbsp; &nbsp;<span style="color: #666699; font-weight: bold;">throw</span> <span style="color: #333;">&#40;</span><span style="color: #0066cc; font-style: italic;">new-<span style="font-style: normal;">object</span></span> IO.<span style="color: #003366;">DirectoryNotFoundException</span><span style="color: #333;">&#41;</span>; <span style="color: #0066cc; font-style: italic;">write-<span style="font-style: normal;">host</span></span> <span style="color: #009900;">&quot;World!&quot;</span>; <br />
&nbsp; &nbsp;<span style="color: #0066cc; font-style: italic;">write-<span style="font-style: normal;">host</span></span> <span style="color: #009900;">&quot;Hello World!&quot;</span>;<br />
<span style="color: #333;">&#125;</span></div><div class="txt code txt" style="font-family:monospace;">&nbsp; &nbsp;Hello<br />
&nbsp; &nbsp;TRAPPED: System.IO.DirectoryNotFoundException<br />
&nbsp; &nbsp;TRAPPED: Attempted to access a path that is not on the disk.<br />
&nbsp; &nbsp;World!<br />
&nbsp; &nbsp;Hello World!</div>

	<p>As you can see, the trap is trapping the lowest level [Exception] class, </p>

	<p>NOTE: Trapping the [Exception] class is not generally a good idea, since it traps <span class="caps">EVERY</span> possible exception, including out-of-memory, and your error handling will likely not be able to account for all possibilities&#8230;  However, this is fairly acceptable in script, and is certainly no more dangerous than using the <code>$ErrorActionPreference = &#34;SilentlyContinue&#34;</code> option  <img src='http://huddledmasses.org/wordpress/wp-includes/' alt=';)' class='wp-smiley' /> .</p>

	<p>In this example, we used <code>continue</code> to caused execution to return to the scope the trap is in and execute the next command. It&#8217;s important to note that execution only returns to the scope of the trap, so if the exception was thrown inside a function, or even inside a if statement, and trapped outside of it &#8230; the continue will pick up at the end of the nested scope. Also (no matter what you read in books), execution continues at the <strong>next command</strong>, not the next line, so you can&#8217;t pull tricks by putting multiple semicolon-separated commands on the same line.  </p>

	<p>We could have used <code>break</code> instead, which would basically result in re-throwing the exception, so it can be trapped and handled by further traps. For example, try this code:</p>

	<div class="posh code posh" style="font-family:monospace;"><br />
<span style="color: #666699; font-weight: bold;">Function</span> <span style="color: #0066cc; font-style: italic;">Test-<span style="font-style: normal;">Trap2</span></span><span style="color: #333;">&#40;</span><span style="color: #333;">&#41;</span> <span style="color: #333;">&#123;</span><br />
&nbsp; &nbsp;<span style="color: #666699; font-weight: bold;">trap</span> <span style="color: #003366; font-weight: bold;"><span style="color: #333;">&#91;</span>Exception<span style="color: #333;">&#93;</span></span> <span style="color: #333;">&#123;</span> <br />
&nbsp; &nbsp; &nbsp; <span style="color: #0066cc; font-style: italic;">write-<span style="font-style: normal;">host</span></span> <span style="color: #009900;">&quot;Trapped $($_.Exception.Message) in the Outer Trap!&quot;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #666699; font-weight: bold;">continue</span><br />
&nbsp; &nbsp;<span style="color: #333;">&#125;</span><br />
&nbsp; &nbsp;<br />
&nbsp; &nbsp;<span style="color: #666699; font-weight: bold;">if</span><span style="color: #333;">&#40;</span><span style="color: #660033; font-weight: bold;">$true</span><span style="color: #333;">&#41;</span><span style="color: #333;">&#123;</span> <span style="color: #666666; font-style: italic;"># a nested scope</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #666699; font-weight: bold;">trap</span> <span style="color: #003366; font-weight: bold;"><span style="color: #333;">&#91;</span>Exception<span style="color: #333;">&#93;</span></span> <span style="color: #333;">&#123;</span> <br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #0066cc; font-style: italic;">write-<span style="font-style: normal;">host</span></span> <span style="color: #009900;">&quot;Trapped $($_.Exception.Message) in the Inner Trap!&quot;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #666699; font-weight: bold;">break</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #333;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #666699; font-weight: bold;">throw</span> <span style="color: #009900;">&quot;Some Fun&quot;</span>;<br />
&nbsp; &nbsp; &nbsp; <span style="color: #009900;">&quot;We won't reach this!&quot;</span><br />
&nbsp; &nbsp;<span style="color: #333;">&#125;</span><br />
&nbsp; &nbsp;<span style="color: #009900;">&quot;Wasn't that fun?&quot;</span><br />
<span style="color: #333;">&#125;</span><br />
<span style="color: #666666; font-style: italic;">## Will output:</span><br />
<span style="color: #666666; font-style: italic;"># Trapped Some Fun in the Inner Trap!</span><br />
<span style="color: #666666; font-style: italic;"># Trapped Some Fun in the Outer Trap!</span><br />
<span style="color: #666666; font-style: italic;"># Wasn't that fun?</span></div>

	<h4>Trap Scope</h4>

	<p>So far, so good, right? A more complicated example will show off some of the problems. Excuse me for introducing a parameter which allows you to trigger an extra exception, but it will allow you to see the multiple exception traps working, and I&#8217;ll use the implicit <code>trap { ... }</code> syntax for trapping the . NOTE: this code <strong>does not</strong> function as you might expect, so please try it out&#8230;</p>

	<div class="posh code posh" style="font-family:monospace;"><br />
<span style="color: #666699; font-weight: bold;">Function</span> <span style="color: #0066cc; font-style: italic;">Test-<span style="font-style: normal;">Trap3</span></span><span style="color: #333;">&#40;</span><span style="color: #003366; font-weight: bold;"><span style="color: #333;">&#91;</span><span style="color: #666699; font-weight: bold;">switch</span><span style="color: #333;">&#93;</span></span><span style="color: #660033; font-weight: bold;">$CauseProblems</span><span style="color: #333;">&#41;</span> <span style="color: #333;">&#123;</span><br />
&nbsp; &nbsp;<span style="color: #660033; font-weight: bold;">$result</span> <span style="color: #66cc66;">=</span> <span style="color: #660033; font-weight: bold;">$true</span><br />
&nbsp; &nbsp;<span style="color: #666699; font-weight: bold;">if</span><span style="color: #333;">&#40;</span><span style="color: #660033; font-weight: bold;">$CauseProblems</span><span style="color: #333;">&#41;</span> <span style="color: #333;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #009900;">&quot;Try to create a folder, but it's parent doesn't exist so throw:&quot;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #666699; font-weight: bold;">throw</span> <span style="color: #333;">&#40;</span><span style="color: #0066cc; font-style: italic;">new-<span style="font-style: normal;">object</span></span> IO.<span style="color: #003366;">DirectoryNotFoundException</span><span style="color: #333;">&#41;</span>;<br />
&nbsp; &nbsp;<span style="color: #333;">&#125;</span> <span style="color: #666699; font-weight: bold;">else</span> <span style="color: #333;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #009900;">&quot;Created a folder, now fake a problem creating a file.&quot;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #666699; font-weight: bold;">throw</span> <span style="color: #009900;">&quot;Couldn't create a file&quot;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #666666; font-style: italic;"># you'd see this if continue returned into this scope</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #009900;">&quot;Created the file with no problems&quot;</span> <br />
&nbsp; &nbsp;<span style="color: #333;">&#125;</span><br />
<br />
&nbsp; &nbsp;<span style="color: #009900;">&quot;Returning the result...&quot;</span> <span style="color: #666666; font-style: italic;"># ought to be false, but won't be.</span><br />
&nbsp; &nbsp;<span style="color: #666699; font-weight: bold;">return</span> <span style="color: #660033; font-weight: bold;">$result</span><br />
&nbsp; &nbsp;<br />
&nbsp; &nbsp;<span style="color: #666666; font-style: italic;"># an interesting feature of powershell is that it doesn't care the order of the traps...</span><br />
&nbsp; &nbsp;<span style="color: #666699; font-weight: bold;">trap</span> <span style="color: #003366; font-weight: bold;"><span style="color: #333;">&#91;</span>IO.<span style="color: #003366;">DirectoryNotFoundException</span><span style="color: #333;">&#93;</span></span> <span style="color: #333;">&#123;</span> <br />
&nbsp; &nbsp; &nbsp; <span style="color: #0066cc; font-style: italic;">write-<span style="font-style: normal;">host</span></span> <span style="color: #009900;">&quot;Can't find that directory!&quot;</span>; <br />
&nbsp; &nbsp; &nbsp; <span style="color: #660033; font-weight: bold;">$result</span> <span style="color: #66cc66;">=</span> <span style="color: #660033; font-weight: bold;">$false</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #666699; font-weight: bold;">break</span>; <br />
&nbsp; &nbsp;<span style="color: #333;">&#125;</span><br />
&nbsp; &nbsp;<span style="color: #666699; font-weight: bold;">trap</span> <span style="color: #333;">&#123;</span> <br />
&nbsp; &nbsp; &nbsp; <span style="color: #0066cc; font-style: italic;">write-<span style="font-style: normal;">host</span></span> <span style="color: #009900;">&quot;<span style="color: #000099; font-weight: bold;">`$</span>Result started set to $result.&quot;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #0066cc; font-style: italic;">write-<span style="font-style: normal;">host</span></span> $<span style="color: #333;">&#40;</span><span style="color: #009900;">&quot;<span style="color: #000099; font-weight: bold;">`t</span>TRAPPED: &quot;</span> <span style="color: #66cc66;">+</span> <span style="color: #660033; font-weight: bold;">$_</span>.<span style="color: #003366;">Exception</span>.<span style="color: #003366;">GetType</span><span style="color: #333;">&#40;</span><span style="color: #333;">&#41;</span>.<span style="color: #003366;">FullName</span><span style="color: #333;">&#41;</span>; <br />
&nbsp; &nbsp; &nbsp; <span style="color: #0066cc; font-style: italic;">write-<span style="font-style: normal;">host</span></span> $<span style="color: #333;">&#40;</span><span style="color: #009900;">&quot;<span style="color: #000099; font-weight: bold;">`t</span>TRAPPED: &quot;</span> <span style="color: #66cc66;">+</span> <span style="color: #660033; font-weight: bold;">$_</span>.<span style="color: #003366;">Exception</span>.<span style="color: #003366;">Message</span><span style="color: #333;">&#41;</span>; <br />
&nbsp; &nbsp; &nbsp; <span style="color: #660033; font-weight: bold;">$result</span> <span style="color: #66cc66;">=</span> <span style="color: #660033; font-weight: bold;">$false</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #0066cc; font-style: italic;">write-<span style="font-style: normal;">host</span></span> <span style="color: #009900;">&quot;<span style="color: #000099; font-weight: bold;">`$</span>Result is now set to $result, since you had a problem&quot;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #666699; font-weight: bold;">continue</span>; <br />
&nbsp; &nbsp;<span style="color: #333;">&#125;</span><br />
<span style="color: #333;">&#125;</span></div>

	<p>When you execute that with and without the -CauseProblems switch, you&#8217;ll see a few odd things develop.  </p>

	<div class="txt code txt" style="font-family:monospace;"><br />
PS &gt; Test-Trap3<br />
Created a folder, now fake a problem creating a file.<br />
$Result started set to True.<br />
&nbsp; &nbsp; &nbsp; &nbsp; TRAPPED: System.Management.Automation.RuntimeException<br />
&nbsp; &nbsp; &nbsp; &nbsp; TRAPPED: Couldn't create a file<br />
$Result is now set to False, since you had a problem<br />
Returning the result...<br />
True<br />
<br />
PS &gt; Test-Trap3 -Cause<br />
Try to create a folder, but it's parent doesn't exist so throw:<br />
Can't find that directory!<br />
Attempted to access a path that is not on the disk.<br />
At line:5 char:14<br />
+ &nbsp; &nbsp; &nbsp; &nbsp; throw &nbsp;&lt;&lt;&lt;&lt; (new-object IO.DirectoryNotFoundException);<br />
&nbsp;</div>

	<p>First: regardless of the value of $ErrorActionPreference, when you call <code>Test-Trap2 -Cause</code> you will get an ugly red exception message when we hit line 20 (break) which will be identified as coming from the original source of the exception: line 5 (where we throw the DirectoryNotFoundException).  That&#8217;s weird because it seems to ignore or override the &#8220;SilentlyContinue&#8221; setting, but since that&#8217;s probably what you wanted, I guess it&#8217;s ok.</p>

	<p>Second: regardless (again) of the value of $ErrorActionPreference, when you do <span class="caps">NOT</span> set the -Cause flag, the function will return <code>True</code> every time. Even though in our error handler we were able to access the value of $Result and see that it was <code>True</code> &#8230; and even though we set it to $False, and printed it out so you could see it was set &#8230; the function still returns <code>True</code>, because the trap scope doesn&#8217;t modify the external scope unless you explicitly set the scope of a variable.  <strong>NOTE:</strong> If you had used <code>$script:result</code> instead of <code>$result</code> (in every instance where $result appears in that script), you would get the output which the string/comments led you to expect.</p>

	<p>Third: continue sends execution to &#8220;the next command&#8221; but only if the trap is in the same scope as the line which throws the exception.  So you&#8217;ll never see the message from line 10: &#8220;Created the file with no problems&#8221; because although the error handler calls <code>continue</code>, it continues at the next command that&#8217;s within the same scope as the trap, so if the exception is in a nested scope (inside an if, while, switch, etc) a trap outside that scop can only continue at the end of the scope.</p>

	<h4>Trap Return</h4>

	<p>According to <a href="http://64.233.169.104/search?q=cache:vo1cixTB8RIJ:www.sapienpress.com/powershell.pdf">Chapter 11</a> of Don Jones&#8217; and Jeffery Hicks&#8217; book Windows PowerShell: <span class="caps">TFM</span>, there are actually three actions you can take inside a trap: <code>break</code> and <code>continue</code> which I mentioned above, and <code>return [argument]</code>. However, unlike break and continue, return is affected by the setting of $ErrorActionPreference, which makes it <a href="https://connect.microsoft.com/feedback/ViewFeedback.aspx?FeedbackID=303422&#38;SiteID=99">unpredictable and basically broken</a> &#8230; if you want to output something from a trap error handler, you&#8217;re better off using <code>Write-Output</code> followed by a <code>break</code> or <code>continue</code> (which, incidentally, gives you more flexibility).</p>

	<h4>Try-Catch-Finally</h4>

	<p>If you&#8217;re coming from a C# world, and just want to know how you can do what you&#8217;re used to, here&#8217;s a simple try-catch version:</p>

	<div class="posh code posh" style="font-family:monospace;"><br />
<span style="color: #666699; font-weight: bold;">Function</span> <span style="color: #0066cc; font-style: italic;">Test-<span style="font-style: normal;">TryCatch</span></span><span style="color: #333;">&#40;</span><span style="color: #003366; font-weight: bold;"><span style="color: #333;">&#91;</span><span style="color: #666699; font-weight: bold;">switch</span><span style="color: #333;">&#93;</span></span><span style="color: #660033; font-weight: bold;">$One</span><span style="color: #333;">&#41;</span> <span style="color: #333;">&#123;</span><br />
&nbsp; &nbsp;<span style="color: #66cc66;">&amp;</span><span style="color: #333;">&#123;</span><span style="color: #666666; font-style: italic;">#Try</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #0066cc; font-style: italic;">Write-<span style="font-style: normal;">Host</span></span> <span style="color: #009900;">&quot;Create a DB connection&quot;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #0066cc; font-style: italic;">Write-<span style="font-style: normal;">Host</span></span> <span style="color: #009900;">&quot;Run some db queries&quot;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #666666; font-style: italic;"># throw things for testing purposes</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #666699; font-weight: bold;">if</span><span style="color: #333;">&#40;</span> <span style="color: #660033; font-weight: bold;">$One</span> <span style="color: #333;">&#41;</span> <span style="color: #333;">&#123;</span> <span style="color: #666699; font-weight: bold;">throw</span> <span style="color: #333;">&#40;</span><span style="color: #0066cc; font-style: italic;">new-<span style="font-style: normal;">object</span></span> NullReferenceException<span style="color: #333;">&#41;</span> <span style="color: #333;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #666699; font-weight: bold;">return</span> <span style="color: #009900;">&quot;Success!&quot;</span> <span style="color: #666666; font-style: italic;"># you can return if you don't have a &quot;finally&quot;</span><br />
&nbsp; &nbsp;<span style="color: #333;">&#125;</span><br />
&nbsp; &nbsp;<span style="color: #666666; font-style: italic;">### CATCH NullReference and IndexOutOfRange, etc</span><br />
&nbsp; &nbsp;<span style="color: #666699; font-weight: bold;">trap</span> <span style="color: #003366; font-weight: bold;"><span style="color: #333;">&#91;</span>SystemException<span style="color: #333;">&#93;</span></span> <span style="color: #333;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #0066cc; font-style: italic;">Write-<span style="font-style: normal;">Host</span></span> <span style="color: #009900;">&quot;Data access failed because $_&quot;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #0066cc; font-style: italic;">Write-<span style="font-style: normal;">Output</span></span> <span style="color: #009900;">&quot;Failure!&quot;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #666699; font-weight: bold;">continue</span> <span style="color: #666666; font-style: italic;"># So that the &quot;Finally&quot; stuff gets executed</span><br />
&nbsp; &nbsp;<span style="color: #333;">&#125;</span><br />
<span style="color: #333;">&#125;</span></div>

	<p>Now, if you have a more complicated scenario and you need a finally clause, you can replace the &#8220;return&#8221; in the try clause with a Write-Output, and then any code at the end, after the trap(s), basically becomes your finally clause.  An even more complicated scenario is if you need to rethrow an exception &#8212; lets say, you catch it just to log it, or you catch it and then decide you can&#8217;t correct for it.  Normally you would just <code>break</code> at that point, but if you have clean up code you need to execute (a finally clause) then you can&#8217;t break, so instead you have to store the error record and then rethrow it later by hand.  The catch is &#8230; you have to make sure that the traps don&#8217;t retrap it (you would end up in an infinite loop), so you have to create an extra layer of scope, which you can do using the &#038; execute operator, like this:</p>

	<div class="posh code posh" style="font-family:monospace;"><br />
<span style="color: #666699; font-weight: bold;">Function</span> <span style="color: #0066cc; font-style: italic;">Test-<span style="font-style: normal;">TryCatch</span></span><span style="color: #333;">&#40;</span><span style="color: #003366; font-weight: bold;"><span style="color: #333;">&#91;</span><span style="color: #666699; font-weight: bold;">switch</span><span style="color: #333;">&#93;</span></span><span style="color: #660033; font-weight: bold;">$One</span>,<span style="color: #003366; font-weight: bold;"><span style="color: #333;">&#91;</span><span style="color: #666699; font-weight: bold;">switch</span><span style="color: #333;">&#93;</span></span><span style="color: #660033; font-weight: bold;">$Two</span>,<span style="color: #003366; font-weight: bold;"><span style="color: #333;">&#91;</span><span style="color: #666699; font-weight: bold;">switch</span><span style="color: #333;">&#93;</span></span><span style="color: #660033; font-weight: bold;">$Three</span><span style="color: #333;">&#41;</span> <span style="color: #333;">&#123;</span><br />
&nbsp; &nbsp;<span style="color: #660033; font-weight: bold;">$script</span>:Exception <span style="color: #66cc66;">=</span> <span style="color: #660033; font-weight: bold;">$null</span>;<br />
&nbsp; &nbsp;<span style="color: #666666; font-style: italic;"># We have a finally clause and need to rethrow exceptions</span><br />
&nbsp; &nbsp;<span style="color: #666666; font-style: italic;"># So we nest the try and all the traps inside a scope...</span><br />
&nbsp; &nbsp;<span style="color: #66cc66;">&amp;</span><span style="color: #333;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #66cc66;">&amp;</span><span style="color: #333;">&#123;</span><span style="color: #666666; font-style: italic;">#TRY</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #0066cc; font-style: italic;">Write-<span style="font-style: normal;">Host</span></span> <span style="color: #009900;">&quot;Create a DB connection&quot;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #0066cc; font-style: italic;">Write-<span style="font-style: normal;">Host</span></span> <span style="color: #009900;">&quot;Run some db queries&quot;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #666666; font-style: italic;"># throw things for testing purposes</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #666699; font-weight: bold;">if</span><span style="color: #333;">&#40;</span> <span style="color: #660033; font-weight: bold;">$One</span> &nbsp; <span style="color: #333;">&#41;</span> <span style="color: #333;">&#123;</span> <span style="color: #666699; font-weight: bold;">throw</span> <span style="color: #333;">&#40;</span><span style="color: #0066cc; font-style: italic;">new-<span style="font-style: normal;">object</span></span> NullReferenceException<span style="color: #333;">&#41;</span> <span style="color: #333;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #666699; font-weight: bold;">if</span><span style="color: #333;">&#40;</span> <span style="color: #660033; font-weight: bold;">$Two</span> &nbsp; <span style="color: #333;">&#41;</span> <span style="color: #333;">&#123;</span> <span style="color: #666699; font-weight: bold;">throw</span> <span style="color: #333;">&#40;</span><span style="color: #0066cc; font-style: italic;">new-<span style="font-style: normal;">object</span></span> IndexOutOfRangeException<span style="color: #333;">&#41;</span> <span style="color: #333;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #666699; font-weight: bold;">if</span><span style="color: #333;">&#40;</span> <span style="color: #660033; font-weight: bold;">$Three</span> <span style="color: #333;">&#41;</span> <span style="color: #333;">&#123;</span> <span style="color: #666699; font-weight: bold;">throw</span> <span style="color: #009900;">&quot;a runtime exception&quot;</span> <span style="color: #333;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #666666; font-style: italic;"># If you need a finally clause, Write-Output, don't return</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #0066cc; font-style: italic;">Write-<span style="font-style: normal;">Output</span></span> <span style="color: #009900;">&quot;Success!&quot;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #333;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #666666; font-style: italic;">### CATCH NullReference and IndexOutOfRangeException</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #666699; font-weight: bold;">trap</span> <span style="color: #003366; font-weight: bold;"><span style="color: #333;">&#91;</span>SystemException<span style="color: #333;">&#93;</span></span> <span style="color: #333;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #0066cc; font-style: italic;">Write-<span style="font-style: normal;">Host</span></span> <span style="color: #009900;">&quot;Data access failed because $_&quot;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #0066cc; font-style: italic;">Write-<span style="font-style: normal;">Output</span></span> <span style="color: #009900;">&quot;Failure!&quot;</span> <span style="color: #666666; font-style: italic;"># Instead of return, when in a trap</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #666699; font-weight: bold;">continue</span> <span style="color: #666666; font-style: italic;"># So that the &quot;Finally&quot; stuff gets executed</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #333;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #666666; font-style: italic;">### CATCH ... the other thing</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #666699; font-weight: bold;">trap</span> <span style="color: #003366; font-weight: bold;"><span style="color: #333;">&#91;</span>Management.<span style="color: #003366;">Automation</span>.<span style="color: #003366;">RuntimeException</span><span style="color: #333;">&#93;</span></span> <span style="color: #333;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #0066cc; font-style: italic;">Write-<span style="font-style: normal;">Host</span></span> <span style="color: #009900;">&quot;We would write some error-logging code here to log $($_.Exception.Message)&quot;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #0066cc; font-style: italic;">Write-<span style="font-style: normal;">Output</span></span> <span style="color: #009900;">&quot;Failure!&quot;</span> <span style="color: #666666; font-style: italic;"># Instead of return, when in a trap</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #666666; font-style: italic;"># If we need to rethrow, we have to do it after the &quot;Finally&quot;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #660033; font-weight: bold;">$script</span>:Exception <span style="color: #66cc66;">=</span> <span style="color: #660033; font-weight: bold;">$_</span>; <span style="color: #666699; font-weight: bold;">continue</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #333;">&#125;</span><br />
&nbsp; &nbsp;<span style="color: #333;">&#125;</span> <span style="color: #666666; font-style: italic;"># end the extra scope before the finally</span><br />
&nbsp; &nbsp;<span style="color: #666666; font-style: italic;">#### FINALLY always gets executed</span><br />
&nbsp; &nbsp;<span style="color: #0066cc; font-style: italic;">Write-<span style="font-style: normal;">Host</span></span> <span style="color: #009900;">&quot;Clean up and close the DB connection&quot;</span> &nbsp;<span style="color: #000066;">-foreground</span> green<br />
&nbsp; &nbsp;<span style="color: #666666; font-style: italic;">#### Rethrow the exception if need be...</span><br />
&nbsp; &nbsp;<span style="color: #666699; font-weight: bold;">if</span><span style="color: #333;">&#40;</span><span style="color: #660033; font-weight: bold;">$script</span>:Exception <span style="color: #000066;">-ne</span> <span style="color: #660033; font-weight: bold;">$null</span><span style="color: #333;">&#41;</span> <span style="color: #333;">&#123;</span> <span style="color: #666699; font-weight: bold;">throw</span> <span style="color: #333;">&#40;</span><span style="color: #660033; font-weight: bold;">$script</span>:Exception<span style="color: #333;">&#41;</span> <span style="color: #333;">&#125;</span><br />
&nbsp; &nbsp;<br />
&nbsp; &nbsp;<span style="color: #666666; font-style: italic;"># If you had code after your try-catch-finally, it would be here...</span><br />
<span style="color: #333;">&#125;</span></div>

	<h4> <img src='http://huddledmasses.org/wordpress/wp-includes/' alt='[new]' class='wp-smiley' />  Postscript</h4>

	<p><a href="http://cashfoley.com/">Cash Foley</a> points out an alternate <a href="http://weblogs.asp.net/adweigert/archive/2007/10/10/powershell-try-catch-finally-comes-to-life.aspx">try -catch -finally function by Adam Weigert</a> which works great, and simplifies your code substantially by encapsulating the scope-nesting into a function &#8212; as long as you&#8217;re able to handle all of your exceptions in a single trap.</p>]]></content:encoded>
			<wfw:commentRss>http://huddledmasses.org/trap-exception-in-powershell/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

