How does try catch work?
-
Monday, September 10, 2012 10:27 AM
How does try catch work?
Does anyone have any suggestions?
Thanks in advance for any suggestions
try {
$request = [System.Net.WebRequest]::Create($url)
$request.Method = 'HEAD'
$response = $request.GetResponse()
$httpStatus = $response.StatusCode,I would like to know if it gets error here, will it jump directly into catch section? and skip the rest of following checking?
$urlIsValid = ($httpStatus -eq 'OK')
$tryError = $null
}
catch [System.Exception] {
$httpStatus = $null
$urlIsValid = $false;$tryError = $_.Exception
}Thanks in advance for any suggestions
All Replies
-
Monday, September 10, 2012 10:33 AM
If a line raises an exception (error), the code will jump directly to the catch statement. Any code in the try block after the failed line will not be executed.Grant Ward, a.k.a. Bigteddy
- Marked As Answer by oem7110 Monday, September 10, 2012 11:12 AM
-
Monday, September 10, 2012 11:13 AMThanks you very much for suggestions :>
Thanks in advance for any suggestions
-
Monday, September 10, 2012 2:12 PM
Start by learning to use help. At a PowerShell prompt type:
help help
Now try:
help try
Always review the help material before asking simple questions.
¯\_(ツ)_/¯
-
Wednesday, September 12, 2012 4:55 AMThanks everyone very much for suggestions
Thanks in advance for any suggestions
-
Wednesday, September 12, 2012 7:03 AM
The try will only catch stopping exception, you can add -erroraction stop on non-stopping exception
$httpStatus = $response.StatusCode will no throw exception here, because the StatusCode will contain what you need, a wrong URI is not a error in the contex of a software. You need to use if else statment like
if ($response.StatusCode -like "yourcondition) { # everything ok here
} else { # everything wrong here }
- Edited by Bruce JDCMicrosoft Community Contributor Wednesday, September 12, 2012 9:02 AM

