Error handling
Chapter 2, PowerShell Peculiarities introduced PowerShell's two error-handling mechanisms: the trap
statement and the try
, catch
, and finally
statements. That chapter explained how these statements function in PowerShell code. The following sections will give you some guidance on how to use them effectively and some techniques for writing error-handling code.
Error-handling guidelines
The first thing to mention is that although the trap
statement can be effective for handling errors, its flow can be confusing, especially when considering the many ways to exit a trap statement. For this reason, it is a good idea to avoid the trap
statement in most cases and use the try
/ catch
/ finally
constructions instead. Since environments that only support PowerShell Version 1.0 are not very common, try
, catch
, and finally
can be used almost everywhere. Also, the flow of try
/ catch
/ finally
is much more linear, leading to less confusion about the flow of execution.
A second point is that...