Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
1 like 0 dislike
884 views
in PowerShell by 23 24 33

I am using Try Catch in PowerShell, but in some cases, the errors aren’t getting caught

try {
   
}

catch {
    "An error occurred that could not be resolved."
}

I also tried to use the below code but still not working

try {
   
}
catch [System.Net.WebException],[System.IO.IOException] {
    " "An error occurred that could not be resolved."
}

Am I missing something, and Why Try Catch is not working in PowerShell?


1 Answer

2 like 0 dislike
by 152 169 345
selected by
 
Best answer

Error Handling in PowerShell

In PowerShell, you can use use the try, catch, and finally blocks to handle terminating errors and stops a statement from running.

  • A try block is used to define a section of a script in which you want PowerShell to monitor for errors.
  • A catch block is used to handle the error.
  • A finally block can be used to free any resources that are no longer needed by your script.

Try, Catch Finally Syntax

try { 
   # your code
}
catch {
 
  Write-Host "An error occurred:"
  # to get error details, use one of the below 
  Write-Host $_ 
  Write-Host $Error
  Write-Host $_.Exception
}
finally{
    # free any resources that are no longer needed
}

Output
Try catch in PowerShell

When an error occurs within the try block, the error is first saved to the $Error automatic variable, and If the error cannot be handled, the error is written to the error stream.


Solving: Try, Catch is not working in PowerShell

In your case, if your code is not getting caught, try to use -ErrorAction stop as below

try { 
   # your code  -ErrorAction stop
}
catch {
  Write-Host "An error occurred:"
  Write-Host $Error
}
If you don’t ask, the answer is always NO!
...