?
Solved

Powershell Exeception Question

Posted on 2012-03-20
7
Medium Priority
?
383 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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 2000 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

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

Question has a verified solution.

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

In threads here at EE, each comment has a unique Identifier (ID). It is easy to get the full path for an ID via the right-click context menu. However, we often want to post a short link within a thread rather than the full link. This article shows a…
Auditing domain password hashes is a commonly overlooked but critical requirement to ensuring secure passwords practices are followed. Methods exist to extract hashes directly for a live domain however this article describes a process to extract u…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

752 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