October 2017
Intermediate to advanced
440 pages
11h 47m
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:
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 $_.Exception.Message ...Read now
Unlock full access