Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I rethrow an exception from catch block in PowerShell?

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?

like image 349
pencilCake Avatar asked Dec 11 '12 12:12

pencilCake


People also ask

Is it possible to rethrow a caught exception?

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.

Which keyword is used to Rethrow an exception from catch block?

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).

How do you handle exceptions in catch block?

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.

Why do we need to Rethrow the exception in catch?

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.


1 Answers

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


Note

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.

like image 100
Akim Avatar answered Sep 19 '22 16:09

Akim