PowerShell provides two different ways to handle terminating errors: using try-catch-finally
, or using trap
.
PowerShell 2.0 introduced try-catch-finally
as a means of handling terminating errors.
A try
block must be followed by either one or more catch
blocks, or a finally
block, or both. Each of the following patterns is valid:
try { <script> } catch { <script> } try { <script> } finally { <script> } try { <script> } catch { <script> } finally { <script }
An error occurring within try
will trigger the execution of catch
.
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...