How to catch exceptions in PowerShell?

Question:

If I have a piece of code that throws an exception I get an error message, but I have no idea how to correctly catch (or determine) the exception that is being thrown. Normally I’ll just catch System.Exception which is a bad idea.

Here is an example… I’m trying to create a folder on a drive that doesn’t exist:

I’ve tried catching System.DriveNotFoundException, but rerunning my script still produces the uncaught exception.

Are there any tips as to effectively handling any type of exception?

Answer:

Right after running the command inspect the contents of $error[0]. Look at the Exception property e.g.:

That particular exception would be [System.Management.Automation.DriveNotFoundException].

BTW if you want to “catch” that exception, you will need to convert the non-terminating error into a terminating error using -EA Stop in order for it to generate an exception that you can catch e.g.:

Source:

How to catch exceptions in PowerShell? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply