Powershell-Error-Exceptions


Exception handling

PowerShell supports try/catch/finally, that should feel familiar to all java, .Net developers.

PowerShell Version 1 introduced the trap statement that still works; I prefer try/catch/finally.

Try/Catch/Finally

Example

try {
1/0
"Hello World"
} catch {
"Error caught: $($error[0])"
} 

Copy and Try it

Output
Attempted to divide by zero.
At C:\Users\aryan\Desktop\test.ps1:2 char:3
+ 1/ <<<< 0
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException

Results
Error caught: Attempted to divide by zero.
Finally, Hello World