Sladescross's Blog

Blogging about Sharepoint related stuff

PowerShell Error Handling August 12, 2013

Sometimes when you are writing scripts, you will anticipate that certain things will not work if certain conditions are not met. These examples help you write necessary code to handle anticipated and unexpected errors.

Error object

Error variable called $error.

Every time an error is encountered, the error object is stored in $error variable.

The $error variable is an array of up to 500 members.

When you run any cmdlet, you have the ability to use ErrorVariable, and then store the error that the cmdlet generates in a user-defined variable.

$? is a Boolean value. All it tells you is if the last command was successful (True) or unsuccessful (False, as in our case).

The next variable is LastExitCode. = The variable only applies to external commands and scripts.

In Windows PowerShell 2.0 the Set-StrictMode Windows PowerShell cmdlet is used to catch additional errors. When you use it, you must tell it what mode that you want for it to use. You can make it behave like Windows PowerShell 1.0′s Set-PSDebug -strict and it will only check for uninitialized variables. It does not check for uninitialized variables inside a string. This is illustrated here.

There are three sets of error handling statements included in the PowerShell language:
•Trap – allows you to trap any errors that occur in your code. You define the trap block before any risky code is executed. Trap is part of V1 and included in V2.
•Try/Catch/Finally – these three statements allow you to try some dodgy code, catch any errors that occur in that dodgy code then do any clean up (whether or not an error occurred). Try/catch/finally is an addition to V2 and is not supported in V1.
•Throw – this allows you to detect an error (for example in a subordinate script or function) and throw an error for a higher level script or function to catch or trap. This statement is in both V1 and V2.

In the .Net framework, when an error occurs inside a method which cannot be recovered from inside the method, it’s considered an exceptional circumstance. Since the problem can’t be handled by the method, the exception is raised up to the code which called the method by throwing an error object derived from System.Exception, which has an error message as well as a stack trace and information about the source of the error. In general, the caller can catch the exception and deal with it, or, if it can’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.

In .Net, you can only throw exceptions, but in PowerShell, you can throw pretty much anything … the reason is that when you throw something that is not an Exception, it gets automatically wrapped up into a RuntimeException for you.

Trap –> The first thing you need to know about trapping is that you don’t always have to do it. The $ErrorActionPreference can be set to “Continue” when an error is thrown (or even “SilentlyContinue”) which is basically the equivalent of VB’s ON ERROR RESUME NEXT and doesn’t require any specific error handling code.

if(-not $?) { #handle $Error … The $Error Object is fairly well documented, so I’ll just leave the rest to your experimentation.

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

Trap Return

According to Chapter 11 of Don Jones’ and Jeffery Hicks’ book Windows PowerShell: TFM, there are actually three actions you can take inside a trap: break and continue which I mentioned above, and return [argument]. However, unlike break and continue, return is affected by the setting of $ErrorActionPreference, which makes it unpredictable and basically broken … if you want to output something from a trap error handler, you’re better off using Write-Output followed by a break or continue (which, incidentally, gives you more flexibility).

throw (new-object IO.DirectoryNotFoundException).

Trap scope.

29.PS C:\> $error[0].Exception.StackTrace

Exceptions not to throw and some not to trap! Very few to catch and throw.

Most developers have become comfortable with using exceptions for usage errors such as division by zero or null references. In the Framework, exceptions are used for all error conditions, including execution errors.

X DO NOT return error codes.

Exceptions are the primary means of reporting errors in frameworks.

√ DO report execution failures by throwing exceptions.

√ CONSIDER terminating the process by calling System.Environment.FailFast (.NET Framework 2.0 feature) instead of throwing an exception if your code encounters a situation where it is unsafe for further execution.

X DO NOT use exceptions for the normal flow of control, if possible.

The member used to check preconditions of another member is often referred to as a tester, and the member that actually does the work is called a doer.

There are cases when the Tester-Doer Pattern can have an unacceptable performance overhead. In such cases, the so-called Try-Parse Pattern should be considered (see Exceptions and Performance for more information).

X DO NOT throw exceptions from exception filter blocks.

X AVOID explicitly throwing exceptions from finally blocks. Implicitly thrown exceptions resulting from calling methods that throw are acceptable.

The member used to test a condition, which in our example is the property IsReadOnly, is referred to as the tester. The member used to perform a potentially throwing operation, the Add method in our example, is referred to as the doer.

For extremely performance-sensitive APIs, an even faster pattern than the Tester-Doer Pattern described in the previous section should be used. The pattern calls for adjusting the member name to make a well-defined test case a part of the member semantics. For example, DateTime defines a Parse method that throws an exception if parsing of a string fails. It also defines a corresponding TryParse method that attempts to parse, but returns false if parsing is unsuccessful and returns the result of a successful parsing using an out parameter.


OWSTIMER Cryptography Exception March 21, 2013

Filed under: Cryptograhy,Cryptography,Exception,OWSTIMER — sladescross @ 8:59 pm

Uninstalling Visual Studio will not resolve this issue as the registry settings which present this dialog are still active.

To configure the server to no longer show a dialog when an unhandled exception occurs, use the registry editor to delete the following registry keys:

  • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug\Debugger
  • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\DbgManagedDebugger

On a 64-bit operating system also delete the following registry keys:

  • HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\AeDebug\Debugger
  • HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\DbgManagedDebugger

Worth setting to Automatic the Protected Storage service?



Exception Best Practice July 6, 2012

Filed under: Exception,Resource Exception — sladescross @ 3:35 pm

Don’t use exceptions to indicate absence of a resource

Microsoft recommends that you should use return special values on extremely common situations. I know I just wrote the opposite and I also don’t like it, but life is easier when most APIs are consistent, so I recommend you to adhere to this style with caution.

I looked at the .NET framework, and I noticed that the almost only APIs that use this style are the APIs that return some resource (e.g., Assembly.GetManifestStream method). All those APIs return null in case of the absence of some resource.


Exception Handling May 8, 2012

Tester-Doer pattern.

Use when exception is likely.

Using the Exception Handling block.

Using the Exception Handling Block.


Client object model asynchronous object model exception handling February 28, 2012

Filed under: Exception — sladescross @ 12:20 pm

Client object model asynchronous object model exception handling.





WPF “DispatcherUnhandledException” handler to “App.xaml” November 9, 2011

Filed under: App.xaml,DispatcherUnhandledException,Exception — sladescross @ 11:47 am

The View-Model class that we just implemented throws “Exceptions“. We need to handle these exceptions, otherwise the application will stop. We will implement the exception handler in the code-behind file for the “App.xaml” file as the method “APP_DispatcherUnhandledException“:

Collapse | Copy Code
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Windows;
using System.Linq;
using System.Windows.Threading;

namespace WpfModelViewDemoApplication
    public partial class App : Application
        private void OnStartup(object sender, StartupEventArgs e)
            Views.MainView view = new Views.MainView();
            view.DataContext = new ViewModels.MainViewModel();

        private void APP_DispatcherUnhandledException(object sender, 
            DispatcherUnhandledExceptionEventArgs e)
            e.Handled = true;

In order that the exception handler catches the exceptions, we will need to modify the “App.xaml” file to set the “DispatcherUnhandledException” property in the “<Application />” tag to “APP_DispatcherUnhandledException“:

Collapse | Copy Code
<Application x:Class="WpfModelViewDemoApplication.App"


This exception handler only catches unhandled exceptions thrown from the UI thread. If the application has worker threads that also throw exceptions, these exceptions need to be “Dispatched” to the UI thread to be caught by this handler.



Patterns and Practices Exception Handling Application Block October 7, 2011

Exception Handling Application Block



SPUpdatedConcurrencyException on SPPersistedObject May 24, 2011

catch (SPUpdatedConcurrencyException)
        if (count > 10)


Exception In Constructor February 1, 2010

Filed under: .NET,Constructor,Exception — sladescross @ 11:26 pm


Exception Handling Best Practice December 19, 2009

Filed under: .NET,Error Handling,Exception,HRESULT,Resource — sladescross @ 4:02 pm

As we’re talking about logging, don’t forget that you should always log Exception.ToString(), and never Exception.Message. Exception.ToString() will give you a stack trace, the inner exception and the message. Often, this information is priceless and if you only log Exception.Message, you’ll only have something like “Object reference not set to an instance of an object”.

Microsoft recommends that you should use return special values on extremely common situations. I know I just wrote the opposite and I also don’t like it, but life is easier when most APIs are consistent, so I recommend you to adhere to this style with caution.

I looked at the .NET framework, and I noticed that the almost only APIs that use this style are the APIs that return some resource (e.g., Assembly.GetManifestStream method). All those APIs return null in case of the absence of some resource.

Instead of “throw ex;“, which will throw a new exception and clear the stack trace, we have simply “throw;“. If you don’t specify the exception, the throw statement will simply rethrow the very same exception the catch statement caught. This will keep your stack trace intact, but still allows you to put code in your catch blocks.

An HRESULT is an opaque result handle defined to be zero or positive for a successful return from a function, and negative for a failure. Generally, successful functions return the S_OK HRESULT value (which is equal to zero). But in rare circumstances, functions may return success codes with additional information e.g. S_FALSE=0×01.

HRESULTS were originally defined in the IBM/Microsoft OS/2 operating system as a general purpose error return code, and subsequently adopted in Windows NT. Microsoft Visual Basic substantially enhanced the HRESULT error reporting mechanisms, by associating an IErrorInfo object with an HRESULT error code, by storing a pointer to an IErrorInfo COM object in thread-local storage. The IErrorInfo mechanism allows programs to associate a broad variety of information with a particular HRESULT error: the class of the object that raised the error, the interface of the object that raised the error, error text; and a link to a help topic in a help file. In addition, receivers of an HRESULT error can obtain localized text for the error message on demand.

Subsequently, HRESULT, and the associated IErrorInfo mechanism were used as the default error reporting mechanism in COM.

Support of the IErrorinfo mechanism in Windows is highly inconsistent. Older windows APIs tend to not support it at all, returning HRESULTS without any IErrorInfo data. More modern Windows COM subsystems will often provide extensive error information in the message description of the IErrorInfo object. The more advanced features of the IErrorInfo error mechanisms—help links, and on-demand localization—are rarely used.

In the .NET Framework, HRESULT/IErrorInfo error codes are translated into CLR exceptions when transitioning from native to managed code; and CLR exceptions are translated to HRESULT/IErrorInfo error codes when transitioning from managed to native COM code.



Get every new post delivered to your Inbox.

Join 63 other followers