Solved

Powershell Exeception Question

Posted on 2012-03-20
7
373 Views
Last Modified: 2012-03-22
Hi,

I am trying to understand why a simple try / catch block is not capturing exceptions.

From the code below I expect it the output to be:

Start..
Test1..
Exception 1...
Test2..
Exception 2...

However instead I get:

PS C:\> .\exception_test.ps1
Attempted to divide by zero.
At C:\exception_test.ps1:6 char:10
+     $a = 1 / <<<<  0
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException

PS C:\>

So what am I doing wrong ?

The code is below.

Thanks,

Ward.

PS testPC is a non-existant pc.

write-Host "Start.."

try 
{ 
	Write-Host "Test1.."
	$a = 1 / 0 
}

catch 
{	
	write-host "Exception 1..." 
}

try 
{ 	
	Write-Host "Test2.."
	$wmi_objects = Get-WmiObject "Win32_Process" -computer "testPC" 
}

catch 
{	
	write-host "Exception 2..." 
}

Open in new window

0
Comment
Question by:whorsfall
  • 3
  • 3
7 Comments
 
LVL 16

Expert Comment

by:Dale Harris
ID: 37745465
You can't divide by 0.  

$a = 1 / 0

What exactly are you trying to do?
0
 
LVL 16

Expert Comment

by:Dale Harris
ID: 37745471
Are those supposed to be placeholders for computers you're trying to ping?  If that's the case, it would look something like this:

$Count = $Computers.count

$a = "1/$count"

Does that make sense?
0
 
LVL 8

Expert Comment

by:Brent Challis
ID: 37745535
Your problem with the sample code seems to be that the PowerShell environment is detecting that you have written a divide by zero.  If he code s modified so that it has to run before the problem is detected to try/catch works as you would expect.  e.g.
 Set-StrictMode -Version "Latest"
write-Host "Start.."
$den = 0
try
{
      Write-Host "Test1.."
      $a = 1 / $den
}
catch
{      
      write-host "Exception 1..."
}

try
{       
      Write-Host "Test2.."
      $wmi_objects = Get-WmiObject "Win32_Process" -computer "testPC"
}
catch
{      
      write-host "Exception 2..."
}

produces

Start..
Test1..
Exception 1...
Test2..
Exception 2...
0
Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

 

Author Comment

by:whorsfall
ID: 37745606
Hi,

Hmm. Can u elaborate a bit futther - provide a more detailed explination.

I looked at the Set-StrictMode and still am confused why my orignal code would of not worked.

I am missing the point here :)

Thanks,

Ward
0
 
LVL 16

Expert Comment

by:Dale Harris
ID: 37745650
I think the core of the issue is that you are trying to do an illegal operation to make an error.  The problem is, the try/catch/finally is geared towards legitimate returns of errors.  For example, if you try to ping a null value, I don't think the try/catch would work, but if you try to ping and get an error that the computer could not be reached, it would be thrown to the catch portion.

Does that make sense?
0
 
LVL 8

Accepted Solution

by:
Brent Challis earned 500 total points
ID: 37745662
The Set-StrictMode is simply my standard starting point and is not actually relevant here.  

What seems to be happening is that when you ask PowerShell to run the script it parses it.  In that process is sees that there is a divide by zero issue as you have hard coded the 0 as the denominator, so it errors out.  This can be seen by the fact that the error message turns up before any of the Write-Host cmdlet output that should have occurred before it gets to the error line.  By changing the denominator to a variable the parsing can't determine that there is an error so the code is executed. We get the Write-Host output, then we get a run time error as the division is performed using a variable that has the value of 0 which is processed in the catch block and then we continue through the code..
0
 
LVL 8

Expert Comment

by:Brent Challis
ID: 37745666
You may also need to set the ErrorActionPreference to enable PowerShell to move past the error as well so that the catch block can process the exception:
$ErrorActionPreference = "Stop"
0

Featured Post

Backup Solution for AWS

Read about how CloudBerry Backup fully integrates your backups with Amazon S3 and Amazon Glacier to provide military-grade encryption and dramatically cut storage costs on any platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The Nano Server Image Builder helps you create a custom Nano Server image and bootable USB media with the aid of a graphical interface. Based on the inputs you provide, it generates images for deployment and creates reusable PowerShell scripts that …
The Windows functions GetTickCount and timeGetTime retrieve the number of milliseconds since the system was started. However, the value is stored in a DWORD, which means that it wraps around to zero every 49.7 days. This article shows how to solve t…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question