Solved

Powershell Exeception Question

Posted on 2012-03-20
7
380 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

 

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

Comparison of Amazon Drive, Google Drive, OneDrive

What is Best for Backup: Amazon Drive, Google Drive or MS OneDrive? In this free whitepaper we look at their performance, pricing, and platform availability to help you decide which cloud drive is right for your situation. Download and read the results of our testing for free!

Question has a verified solution.

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

Synchronize a new Active Directory domain with an existing Office 365 tenant
My attempt to use PowerShell and other great resources found online to simplify the deployment of Office 365 ProPlus client components to any workstation that needs it, regardless of existing Office components that may be needing attention.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

726 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