Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to handle a timeout exception?

1,613 views
Skip to first unread message

Frank

unread,
Dec 14, 2009, 5:06:04 PM12/14/09
to
I would like to gracefully break out of a read loop when a timeout
occurs. Example statements:

$port= new-Object System.IO.Ports.SerialPort COM1,115200,None,8,One
$port.ReadTimeout = 10000
$port.Open()
$port.WriteLine("admin")

while($myinput = $port.ReadLine())
{
$myinput
}

With this, I get the exception:

Exception calling "ReadLine" with "0" argument(s): "The operation has
timed out."
At C:\Frank\Script\serial.ps1:16 char:32
+ while($myinput = $port.ReadLine <<<< ())
+ CategoryInfo : NotSpecified: (:) [],
MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException

How do I handle this exception?

I am fairly new to PS.

Regards,
Frank


Clint

unread,
Dec 14, 2009, 6:55:11 PM12/14/09
to
It depends on whether you are using PowerShell version 1 or 2.

IMO, the try/catch/finally in v2 is much more straight-forward:

$port= new-Object System.IO.Ports.SerialPort COM1,115200,None,8,One
$port.ReadTimeout = 10000
$port.Open()
$port.WriteLine("admin")

try
{
while($myinput = $port.ReadLine())
{
$myinput
}
}
catch [TimeoutException]
{
# Error handling code here
}
finally
{
# Any cleanup code goes here
}
# Execution resumes here

However, if you're using v1 then you have to use the trap keyword, I
forget where I got this code originally, but I find it pretty handy:

# Create a new dotted scope for error handling purposes
. {
. { # Here we enter the dotted "Try" code script block
#ENTER CODE TO "TRY" HERE
} # End try script block
trap {
#ENTER "CATCH" ERROR HANDLING CODE HERE
} # End Trap Block
# Execution will resume HERE after trap blocks have executed
# ENTER "FINALLY" CODE HERE
} # End Try/Trap script block

I hope that's not too cryptic. For more info you can use
get-help about_try_catch_finally
get-help about_trap

~Clint

0 new messages