February 2019
Intermediate to advanced
626 pages
15h 51m
English
catch is used to respond to terminating errors raised within try. catch can be used to respond to any exception, or a specific set of exception types. Each of the following is valid, if incomplete:
try { } catch { 'Catches any exception' }
try { } catch [ExceptionType] { 'Catch an exception type' }
try { } catch [ExceptionType1], [ExceptionType2] {
'Catch exception type 1 and 2'
}
In the following example, calling the ToString method on the null variable will throw an exception that triggers catch:
try {
$null.ToString()
} catch {
Write-Host 'This exception has been handled'
}
When working with catch, the error record that was thrown is made available by using either the $_ variable or $PSItem:
try { $null.ToString() } catch { Write-Host ...Read now
Unlock full access