2

I initialize my function with two commands. First, I load a configuration file with Get-Content and secondly, I import a module (Import-Module).

try {
    Get-Content -Raw -Path Wrong-Path -ErrorAction Stop | ConvertFrom-Json
    Import-Module -Name Wrong_Module -Force -ErrorAction Stop
}
catch [System.Management.Automation.ItemNotFoundException], [System.IO.FileNotFoundException]{
    "Catch block 1"
}
catch [System.Management.Automation.RuntimeException]{
    "Catch block 2"
}
catch {
    "Catch block 3"
}

I tested both commands (Get-Content and Import-Module) on their exception type but I only the second catch block is run. However, actually both commands throw an exception which should trigger the first Catch-Block.

Why is the wrong Catch-Exception block triggered?

Alex_P
  • 2,580
  • 3
  • 22
  • 37
  • This is probably because the ItemNotFoundException class inherits the RuntimeException class. I can't bet my life on it though. If you reorder the catches or remove the RuntimeException exception condition, the result changes. – AdminOfThings Aug 08 '19 at 13:06
  • 2
    This appears to be a bug where `catch` clauses are not actually evaluated in order as advertised. PowerShell 6 behaves differently here and hits the first block; PowerShell 5.1 will only do so if the second block is omitted. (Both will ignore the third block if a more specific one applies.) – Jeroen Mostert Aug 08 '19 at 13:11
  • 1
    It looks like it is due to the -ErrorAction Stop flag. Please refer to this answer and it's comment. https://stackoverflow.com/a/6780143/511105 – P-L Aug 08 '19 at 13:17

0 Answers0