Should I approach the exception handling in the same manner as .NET?
Then, how can I re-throw an exception from catch block in PowerShell?
Is throw
is enough? Or would throw $_
be better?
If a catch block cannot handle the particular exception it has caught, you can rethrow the exception. The rethrow expression ( throw without assignment_expression) causes the originally thrown object to be rethrown.
When an exception is cached in a catch block, you can re-throw it using the throw keyword (which is used to throw the exception objects).
Place any code statements that might raise or throw an exception in a try block, and place statements used to handle the exception or exceptions in one or more catch blocks below the try block. Each catch block includes the exception type and can contain additional statements needed to handle that exception type.
Sometimes we may need to rethrow an exception in Java. If a catch block cannot handle the particular exception it has caught, we can rethrow the exception. The rethrow expression causes the originally thrown object to be rethrown.
If you would like to re-throw original exception you could use throw
(most common), or throw $_
, or throw $_.Exception
ps: inside catch
variable $_
is not exception by itself, but System.Management.Automation.ErrorRecord
that contains Exception
The throw
keyword at PowerShell behaves differently then .NET implementation: in .NET you can only throw System.Exceptions
itself or its successors, but in PowerShell, you can throw anything and that is automatically wrapped up into a System.Management.Automation.RuntimeException
. See snippet here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With