Solved

Powershell Exeception Question

Posted on 2012-03-20
7
345 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:bchallis
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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

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:
bchallis 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:bchallis
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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Utilizing an array to gracefully append to a list of EmailAddresses
"Migrate" an SMTP relay receive connector to a new server using info from an old server.
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 this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

760 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now