In a try … catch statement sequence, PowerShell tries to execute the statements of the try block. If an exception is thrown (throw statement), the execution of the statements in the try block is left (for good) and the statements in the catch block are executed.
An optional finally block may follow the catch block. It contains the statements that need to be executed regardless of an exception was thrown in the try block. Usually, the finally block is used for cleaning up resources that might have been allocated in the catch block.
If a class (such as ExOne in the following example) is derived from System.Exception), an object of that type can be specifically caught in the catch handler (catch [ExOne]).
Because ExTwo does not derive from System.Exception, it is not possible to specifically catch this type.
class ExOne : System.Exception {}
class ExTwo {}
function throwException($num) {
if ($num -eq 1) {
throw [ExOne]::new()
}
if ($num -eq 2) {
throw [ExTwo]::new()
}
}
function tryToCatch($num) {
try {
throwException $num
write-host 'no exception'
}
catch [ExOne] {
write-host "Caught: ExOne"
}
catch [ExTwo] {
write-host "Caught: ExTwo"
}
catch {
write-host "Caught neither ExOne nor ExTwo: `$_ = $_"
}
}
tryToCatch 1
#
# Caught: ExOne
tryToCatch 2
#
# Caught neither ExOne nor ExTwo: $_ = ExTwo
tryToCatch 3
#
# no exception