Trying to Catch and Exception

  • Follow


Hi there

Today at lunch I tried to learn how to try and catch an exception.

I've been wanting to learn how to read the registry in prep for the 
Scripting Games :)

Anyway I can't seem to catch the exact exception I can only catch the 
generic system.exception even thought $error tell me I have write name.

Could someone else try for me

<code>
$ErrorActionPreference = "stop"
Try { Get-ItemProperty -Path "HKCU:\Control Panel\Desktop\" -Name Wallpaper2 }
Catch [System.Management.Automation.PSArgumentException] {  "caught a 
PSArgumentException" }
Catch [system.exception] { "caught a system.exception" }
Finally {  "end of script" }
</code>

$error display's

SMessageDetails      : 
Exception             : System.Management.Automation.PSArgumentException: 
Prope
                        rty Wallpaper2 does not exist at path 
HKEY_CURRENT_USER
                        \Control Panel\Desktop\.
TargetObject          : Wallpaper2
CategoryInfo          : InvalidArgument: (Wallpaper2:String) 
[Get-ItemProperty]
                        , PSArgumentException
FullyQualifiedErrorId : 
System.Management.Automation.PSArgumentException,Micros
                        oft.PowerShell.Commands.GetItemPropertyCommand
ErrorDetails          : 
InvocationInfo        : System.Management.Automation.InvocationInfo
PipelineIterationInfo : {0, 1}

Is anyone able to help me understand where I'm going wrong?

TIA

0
Reply Utf 3/30/2010 2:16:08 PM

I tried:

#####
try
{
Set-Location z:\ -ErrorAction stop
}
catch [System.Management.Automation.DriveNotFoundException]
{
	Write-Host $_.exception.gettype().fullname
	Write-Host $_.exception.message
}

"Gary" wrote:

> Hi there
> 
> Today at lunch I tried to learn how to try and catch an exception.
> 
> I've been wanting to learn how to read the registry in prep for the 
> Scripting Games :)
> 
> Anyway I can't seem to catch the exact exception I can only catch the 
> generic system.exception even thought $error tell me I have write name.
> 
> Could someone else try for me
> 
> <code>
> $ErrorActionPreference = "stop"
> Try { Get-ItemProperty -Path "HKCU:\Control Panel\Desktop\" -Name Wallpaper2 }
> Catch [System.Management.Automation.PSArgumentException] {  "caught a 
> PSArgumentException" }
> Catch [system.exception] { "caught a system.exception" }
> Finally {  "end of script" }
> </code>
> 
> $error display's
> 
> SMessageDetails      : 
> Exception             : System.Management.Automation.PSArgumentException: 
> Prope
>                         rty Wallpaper2 does not exist at path 
> HKEY_CURRENT_USER
>                         \Control Panel\Desktop\.
> TargetObject          : Wallpaper2
> CategoryInfo          : InvalidArgument: (Wallpaper2:String) 
> [Get-ItemProperty]
>                         , PSArgumentException
> FullyQualifiedErrorId : 
> System.Management.Automation.PSArgumentException,Micros
>                         oft.PowerShell.Commands.GetItemPropertyCommand
> ErrorDetails          : 
> InvocationInfo        : System.Management.Automation.InvocationInfo
> PipelineIterationInfo : {0, 1}
> 
> Is anyone able to help me understand where I'm going wrong?
> 
> TIA
> 
0
Reply Utf 4/4/2010 11:54:01 PM


Hmm.  Strange indeed.  I'm not really sure what's going on, but I seem 
to be able to create the same issue.  For instance:

*** try/catch blocks, terminating error WITHOUT -erroraction STOP ***
PS # gieugnwiu
The term 'gieugnwiu' is not recognized as the name of a cmdlet, 
function, script file, or operable program. Check the spelling of the 
name, or if a path was included, verify that the path is correct and try 
again.
at line:1 char:10
+ gieugnwiu <<<<
     + CategoryInfo          : ObjectNotFound: (gieugnwiu:String) [], 
CommandNotFoundException
     + FullyQualifiedErrorId : CommandNotFoundException

PS # $error[0].exception.psobject.typenames
System.Management.Automation.CommandNotFoundException
System.Management.Automation.RuntimeException
System.SystemException
System.Exception
System.Object

PS # try { gieugnwiu } catch 
[System.Management.Automation.CommandNotFoundException] { 'Got it' }
Got it

So that seems to work as one would expect.  We catch the most specific 
exception type, and all is well.  However, when forcing the termination 
with -erroraction stop or by setting $erroractionpreference to "Stop", 
it doesn't seem to work the same.

*** try/catch blocks, force termination with $erroractionpreference ***

PS # $ErrorActionPreference = "Stop"
PS # gci oweifjowe
Get-ChildItem : Cannot find path 'C:\Users\Clint\oweifjowe' because it 
does not exist.
At 
C:\Users\Clint\Documents\WindowsPowerShell\Modules\pscx\Modules\GetChildItem\Pscx.GetChildItem.psm1:71 
char:32
+                 $scriptCmd = {& <<<<  $wrappedCmd @PSBoundParameters }
     + CategoryInfo          : ObjectNotFound: 
(C:\Users\Clint\oweifjowe:String) [Get-ChildItem], ItemNotFoundException
     + FullyQualifiedErrorId : 
PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

PS # $error[0].Exception.psobject.typenames
System.Management.Automation.ItemNotFoundException
System.Management.Automation.SessionStateException
System.Management.Automation.RuntimeException
System.SystemException
System.Exception
System.Object

There's our exception name, 
System.Management.Automation.ItemNotFoundException, but it doesn't work 
like I would expect:

PS # try { gci oweifjowe } catch 
[System.Management.Automation.ItemNotFoundException] { 'got it '}
Get-ChildItem : Cannot find path 'C:\Users\Clint\oweifjowe' because it 
does not exist.
At 
C:\Users\Clint\Documents\WindowsPowerShell\Modules\pscx\Modules\GetChildItem\Pscx.GetChildItem.psm1:71 
char:32
+                 $scriptCmd = {& <<<<  $wrappedCmd @PSBoundParameters }
     + CategoryInfo          : ObjectNotFound: 
(C:\Users\Clint\oweifjowe:String) [Get-ChildItem], ItemNotFoundException
     + FullyQualifiedErrorId : 
PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

Alright, let's try its parent exception:

PS # try { gci oweifjowe } catch 
[System.Management.Automation.SessionStateException] { 'got it '}
Get-ChildItem : Cannot find path 'C:\Users\Clint\oweifjowe' because it 
does not exist.
At 
C:\Users\Clint\Documents\WindowsPowerShell\Modules\pscx\Modules\GetChildItem\Pscx.GetChildItem.psm1:71 
char:32
+                 $scriptCmd = {& <<<<  $wrappedCmd @PSBoundParameters }
     + CategoryInfo          : ObjectNotFound: 
(C:\Users\Clint\oweifjowe:String) [Get-ChildItem], ItemNotFoundException
     + FullyQualifiedErrorId : 
PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

Nope, bugger, how about the grandparent?

PS # try { gci oweifjowe } catch 
[System.Management.Automation.RuntimeException] { 'got it '}
got it

Well, that was caught, but... WHY?  Is there something special about the 
exceptions generated with -ea stop?
0
Reply Clint 4/5/2010 4:47:49 AM

On 3/30/2010 7:16 AM, Gary wrote:
> $ErrorActionPreference = "stop"
> Try { Get-ItemProperty -Path "HKCU:\Control Panel\Desktop\" -Name Wallpaper2 }
> Catch [System.Management.Automation.PSArgumentException] {  "caught a
> PSArgumentException" }
> Catch [system.exception] { "caught a system.exception" }
> Finally {  "end of script" }

Just discovered that the errors that are 'caught' when we force 
termination with the $erroractionpreference or with the -erroraction 
parameter are of type 
System.Management.Automation.ActionPreferenceStopException, and not what 
we see when inspecting $error[0].  So try this code:

Try { Get-ItemProperty -Path "HKCU:\Control Panel\Desktop\" -Name 
Wallpaper2 }
Catch [System.Management.Automation.ActionPreferenceStopExecution] { 
"caught a StopExecution Exception" }
finally { "end of script" }

Instead of trying to trace the errors through the $error variable I used 
the errorvariable parameter in the command, and much to my surprise this 
was the result:

PS # Get-ItemProperty -Path "HKCU:\Control Panel\Desktop\" -Name 
Wallpaper2 -ErrorVariable x
Get-ItemProperty : Property Wallpaper2 does not exist at path 
HKEY_CURRENT_USER\Control Panel\Desktop\.
At line:1 char:17
+ Get-ItemProperty <<<<  -Path "HKCU:\Control Panel\Desktop\" -Name 
Wallpaper2 -ErrorVariable x
     + CategoryInfo          : InvalidArgument: (Wallpaper2:String) 
[Get-ItemProperty], PSArgumentException
     + FullyQualifiedErrorId : 
System.Management.Automation.PSArgumentException,Microsoft.PowerShell.Commands.GetItemPropertyCommand

PS # $x
Command execution stopped because the preference variable 
"ErrorActionPreference" or common parameter is set to Stop: Property 
Wallpaper2 does
  not exist at path HKEY_CURRENT_USER\Control Panel\Desktop\.

PS # $x.Count
1

PS # $x[0].psobject.typenames
System.Management.Automation.ActionPreferenceStopException
System.Management.Automation.RuntimeException
System.SystemException
System.Exception
System.Object

So there we see the ActionPreferenceStopException, and that it is 
derived from the RuntimeException class, which explains the behavior I 
posted earlier.

So the lesson, I suppose, is be careful with handling exceptions thrown 
by erroraction stop!

-- 
v(^_^)~Clint
http://outputredirection.blogspot.com
0
Reply Clint 4/5/2010 5:10:07 AM

Thanks Clint.  Definately something I would not have thought of being new 
to/learning Try/Catch/Final.

Paul


"Clint Bergman" wrote:

> On 3/30/2010 7:16 AM, Gary wrote:
> > $ErrorActionPreference = "stop"
> > Try { Get-ItemProperty -Path "HKCU:\Control Panel\Desktop\" -Name Wallpaper2 }
> > Catch [System.Management.Automation.PSArgumentException] {  "caught a
> > PSArgumentException" }
> > Catch [system.exception] { "caught a system.exception" }
> > Finally {  "end of script" }
> 
> Just discovered that the errors that are 'caught' when we force 
> termination with the $erroractionpreference or with the -erroraction 
> parameter are of type 
> System.Management.Automation.ActionPreferenceStopException, and not what 
> we see when inspecting $error[0].  So try this code:
> 
> Try { Get-ItemProperty -Path "HKCU:\Control Panel\Desktop\" -Name 
> Wallpaper2 }
> Catch [System.Management.Automation.ActionPreferenceStopExecution] { 
> "caught a StopExecution Exception" }
> finally { "end of script" }
> 
> Instead of trying to trace the errors through the $error variable I used 
> the errorvariable parameter in the command, and much to my surprise this 
> was the result:
> 
> PS # Get-ItemProperty -Path "HKCU:\Control Panel\Desktop\" -Name 
> Wallpaper2 -ErrorVariable x
> Get-ItemProperty : Property Wallpaper2 does not exist at path 
> HKEY_CURRENT_USER\Control Panel\Desktop\.
> At line:1 char:17
> + Get-ItemProperty <<<<  -Path "HKCU:\Control Panel\Desktop\" -Name 
> Wallpaper2 -ErrorVariable x
>      + CategoryInfo          : InvalidArgument: (Wallpaper2:String) 
> [Get-ItemProperty], PSArgumentException
>      + FullyQualifiedErrorId : 
> System.Management.Automation.PSArgumentException,Microsoft.PowerShell.Commands.GetItemPropertyCommand
> 
> PS # $x
> Command execution stopped because the preference variable 
> "ErrorActionPreference" or common parameter is set to Stop: Property 
> Wallpaper2 does
>   not exist at path HKEY_CURRENT_USER\Control Panel\Desktop\.
> 
> PS # $x.Count
> 1
> 
> PS # $x[0].psobject.typenames
> System.Management.Automation.ActionPreferenceStopException
> System.Management.Automation.RuntimeException
> System.SystemException
> System.Exception
> System.Object
> 
> So there we see the ActionPreferenceStopException, and that it is 
> derived from the RuntimeException class, which explains the behavior I 
> posted earlier.
> 
> So the lesson, I suppose, is be careful with handling exceptions thrown 
> by erroraction stop!
> 
> -- 
> v(^_^)~Clint
> http://outputredirection.blogspot.com
> .
> 
0
Reply Utf 4/6/2010 3:06:01 AM

I put a little more effort into getting a good resolution to this 
question and posted the results on my blog:

http://outputredirection.blogspot.com/2010/04/powershells-trycatchfinally-and.html

Hope that helps.  If you would like any further clarification just say so :)
-- 
v(^_^)~Clint
http://outputredirection.blogspot.com
0
Reply Clint 4/9/2010 9:24:12 PM

5 Replies
731 Views

(page loaded in 0.07 seconds)


Reply: