I’ve been working with PowerShell’s error handling – trying to get a better handle on it. Yesterday, I looked at general error handling and discussed how to trap or catch an exception. By handling errors in your scripts, you make the script more production ready. And for many, this is a great thing!
One of the problems in trapping or catching an error is knowing what to look for. You can do a blanket catch, such as:
- try {
- ... some dodgy bit of code...
- }
- catch {
- "code broke..."
- }
At one level this works. You can catch an error and avoid your script dying – and maybe returning some interesting info. But there’s often a need to do a better job in detecting different exceptions and handling them differently. As I noted yesterday, a simple script could result in a number of discreet different errors each of which might mean different actions in your script. Along these lines (with PowerShell V2 of course):
- …
- try {
- ... some dodgy bit of code...
- }
- catch [... exception 1]{
- "code broke due to exception 1..."
- }
- catch [... exception 2]{
- "code broke due to exception 2..."
- }
- catch {
- “no idea why your code broke…”
- }
In this second example, you are explicitly testing for two specific exceptions as well as a more general one. The idea here is that for the first two exceptions, you might be able to find some specific information to help the caller (or you) work out what went wrong and deal with it.
The big problem is knowing what exceptions you can trap. I saw a cool script today online - PowerShell Code Repository - Get-Exception. This script looks at all the loaded assemblies and works out what possible exceptions exist and then outputs them. Makes interesting reading and is a great reference.
1 comment:
MOF Repository - Enterprise Architecture Manager is a robust repository that organizes, integrates and analyzes information about an organization's architecture elements.
Post a Comment