locked
Powershell 4.0: Problem with error handling inside Eventhandlers - Powershell has stopped working RRS feed

  • Question

  • Hallo!

    Please see the attached sample code. This code simply show a small WPF-Dialog.

    Test 1 (showing the problem)
    ----------------------------------
    Simply run the program. You will see Powershell crashing "Powershell has stopped working".
    The cause of this is the devision by 0 inside the Eventhandler.
    We would normally expect, that the exception should be handled by the trap.

    Test 2 (showing normal operation)
    ----------------------------------
    Simply remove the comment in line 28 ($i=1/0).
    This activates an exception outside the Eventhandler. Now the Trap will be executed normally.
    --> The exception can be handled by the Powershell Devloper.

    Can anybody help? Why does the Error management via Trap not work inside Eventhandlers?

    Thanks for some assistance and ideas!

    Regards

    Heike

    cls
    Set-StrictMode -Version 4.0
    $ErrorActionPreference = "stop"
    Add-Type -Assemblyname PresentationFramework
    
    
    # -- Eventhandler - will be fired during form load -----------------------------------------------------
    $FormLoaded = {
        Write-Host "EventHandler is running..."               
        # ----------------------------------------------------------------------
        # Problem: 
        # All exceptions will crash Powershell.
        # We would normally expect that the Global Trap will be executed!
        # ----------------------------------------------------------------------
        # This problem occurs inside of Eventhandlers only!
        # ----------------------------------------------------------------------
        
        #  TEST 1  --> Create an Exception (Division by 0) --> Powershell crashes: "Powershell_ISE has stopped working"
        $i=1/0
    }
    # -- End of Eventhandler----------------------------------------------------------------------------------
    
    # -- Start of Demo-Programm ------------------------------------
    Write-Host "Start Demo"
    # -- TEST 2 ---
    # Write-Host "Test 2: Testing Global Trap"
    # Create an Exception (Division by 0) --> Powershell does not crash --> Global Trap will be executed --> OK
    # $i=1/0
    
    # XAML-Code for WPF-Dialog
    [xml]$xaml = @"
    <Window 
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="Test - " Height="370" Width="657" ResizeMode="NoResize" WindowStyle="ThreeDBorderWindow" WindowStartupLocation="CenterScreen" ShowInTaskbar="False"  >
        <Grid Margin="0,0,0,-4">
            <Label Name="CustomerName" Content="Hello World" HorizontalAlignment="Left" Margin="10,2,0,0" VerticalAlignment="Top" Width="596"/>
    
        </Grid>
    </Window>
    "@
    
    $Form1=[Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader $xaml))   # Load form
    
    Write-Host "Register Event"
    $Form1.Add_Loaded($FormLoaded)
    
    Write-Host "Starting ShowDialog"
    $Form1.ShowDialog() > $null
    
    Write-Host "End of program"
    
    # --------------------------------------------------------------------
    # Global Trap - all exceptions should be handled here
    # --------------------------------------------------------------------
     trap{
            Write-host "Global Trap is running..."
            Write-host "End of trap - program will be stopped"
    }

    Monday, January 26, 2015 10:56 AM

Answers

  • It works fine if you don't try to execute the code while loading and if you use a better exception handling method.

    Add-Type -Assemblyname PresentationFramework
    [xml]$xaml=@'
    <Window 
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="Test - " Height="370" Width="657" ResizeMode="NoResize" WindowStyle="ThreeDBorderWindow" WindowStartupLocation="CenterScreen" ShowInTaskbar="False"  >
        <Grid Margin="0,0,0,-4">
            <Label Name="CustomerName" Content="Hello World" HorizontalAlignment="Left" Margin="10,2,0,0" VerticalAlignment="Top" Width="596"/>
    
        </Grid>
    </Window>
    '@
    
    $Form1=[Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader $xaml))   # Load form
    $Form1.Add_Loaded({
        Write-Host "EventHandler is running..."  
        Try{
            $i=1/0
    	}
        Catch{
            Write-Host "$_"
    	}
    })
    
    $Form1.ShowDialog()
    
    


    ¯\_(ツ)_/¯

    • Marked as answer by HeikeP Tuesday, January 27, 2015 3:14 PM
    Monday, January 26, 2015 11:15 AM
  • THis one is even mmore explicit and very easy to manage.

    [xml]$xaml=@'
    <Window 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Test - " Height="370" Width="657" ResizeMode="NoResize" WindowStyle="ThreeDBorderWindow" WindowStartupLocation="CenterScreen" ShowInTaskbar="False"  >
        <Grid Margin="0,0,0,-4">
            <Label Name="CustomerName" Content="Hello World" HorizontalAlignment="Left" Margin="10,2,0,0" VerticalAlignment="Top" Width="596"/>
        </Grid>
    </Window>
    '@
    
    Add-Type -Assemblyname PresentationFramework
    $form1=[Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader $xaml))   # Load form
    $form1.Add_Loaded({
        Try{
            $i=1/0
    	}
        Catch{
            [System.Windows.MessageBox]::Show($_,'Exception','Ok','error')
            $this.Close()
    	}
    })
    
    $form1.ShowDialog()


    ¯\_(ツ)_/¯



    • Edited by jrv Monday, January 26, 2015 11:33 AM
    • Marked as answer by HeikeP Tuesday, January 27, 2015 3:15 PM
    Monday, January 26, 2015 11:31 AM

All replies

  • It works fine if you don't try to execute the code while loading and if you use a better exception handling method.

    Add-Type -Assemblyname PresentationFramework
    [xml]$xaml=@'
    <Window 
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="Test - " Height="370" Width="657" ResizeMode="NoResize" WindowStyle="ThreeDBorderWindow" WindowStartupLocation="CenterScreen" ShowInTaskbar="False"  >
        <Grid Margin="0,0,0,-4">
            <Label Name="CustomerName" Content="Hello World" HorizontalAlignment="Left" Margin="10,2,0,0" VerticalAlignment="Top" Width="596"/>
    
        </Grid>
    </Window>
    '@
    
    $Form1=[Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader $xaml))   # Load form
    $Form1.Add_Loaded({
        Write-Host "EventHandler is running..."  
        Try{
            $i=1/0
    	}
        Catch{
            Write-Host "$_"
    	}
    })
    
    $Form1.ShowDialog()
    
    


    ¯\_(ツ)_/¯

    • Marked as answer by HeikeP Tuesday, January 27, 2015 3:14 PM
    Monday, January 26, 2015 11:15 AM
  • THis one is even mmore explicit and very easy to manage.

    [xml]$xaml=@'
    <Window 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Test - " Height="370" Width="657" ResizeMode="NoResize" WindowStyle="ThreeDBorderWindow" WindowStartupLocation="CenterScreen" ShowInTaskbar="False"  >
        <Grid Margin="0,0,0,-4">
            <Label Name="CustomerName" Content="Hello World" HorizontalAlignment="Left" Margin="10,2,0,0" VerticalAlignment="Top" Width="596"/>
        </Grid>
    </Window>
    '@
    
    Add-Type -Assemblyname PresentationFramework
    $form1=[Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader $xaml))   # Load form
    $form1.Add_Loaded({
        Try{
            $i=1/0
    	}
        Catch{
            [System.Windows.MessageBox]::Show($_,'Exception','Ok','error')
            $this.Close()
    	}
    })
    
    $form1.ShowDialog()


    ¯\_(ツ)_/¯



    • Edited by jrv Monday, January 26, 2015 11:33 AM
    • Marked as answer by HeikeP Tuesday, January 27, 2015 3:15 PM
    Monday, January 26, 2015 11:31 AM
  • Thanks for great and very fast help.

    Due to your hints I have solved the problem.

    I do now use the SourceInitiated event instead of Loaded event. This works fine.

    To switch to »Try-Catch« instead of »Trap« also works fine.

    Thanks for your support!

    Tuesday, January 27, 2015 3:14 PM