Author : MD TAREQ HASSAN | Updated : 2021/10/20

Catch Exception

Catch generic exception

try {
    # ... ... ...
}
catch {

	Write-Error $Error[0] # $Error is an automatic variable available in catch block
	
    return
}

Catch specific exception

try {
    # ... ... ...
}
catch [Xxx]{

	Write-Error $Error[0] # $Error is an automatic variable available in catch block
	
    return
}

About $Error

Extracting exception message

ErrorAction

Usage of “-ErrorAction Stop”: catch exception when exception occurs

$rgResourceId = ''
try {
    $rgResourceId = (Get-AzResourceGroup -Name $Name -ErrorAction Stop).ResourceId
}
catch {
    $exceptionMessage = $Error[0].Exception.Message.Split("-")[1].Trim()
    Write-Warning "Exception message: $exceptionMessage"
}

Usage of “-ErrorAction SilentlyContinue”: checking “ProvisioningState” while performing operation (-AsJob)

try {

    Get-AzResourceGroup -Name $Name -ErrorAction Stop
    | Remove-AzResourceGroup -Force -ErrorAction Stop -AsJob
    | Out-Null

    Write-Host "-------------------------------------------------------------------------------------------`n"

    #Start-Sleep -Seconds 1

    $rg = Get-AzResourceGroup -Name $Name -ErrorAction SilentlyContinue

    while ('Deleting' -eq ${rg}?.ProvisioningState) {

        $currentTimestamp = Get-Date -DisplayHint Time

        Write-Host "[$currentTimestamp] Delete operation in progress...`n"

        #Start-Sleep -Seconds 1

        $rg = Get-AzResourceGroup -Name $Name -ErrorAction SilentlyContinue
    }    

    Write-Host "-------------------------------------------------------------------------------------------`n"
    Write-Host "Resource group '$Name' was deleted successfully`n"
}
catch {
    $exceptionMessage = $Error[0].Exception.Message.Split("-")[1].Trim()
    Write-Warning "Failed to delete resource group '$Name' (Error: $exceptionMessage)`n"
}

Show exception message as warning


$logLocation = "[at $(Split-Path -Path $PSCommandPath -Leaf) function $($MyInvocation.MyCommand.Name)]"

$subscriptionId = ''

try {
    $subscriptionId = (Get-AzSubscription -SubscriptionName $SubscriptionName -ErrorAction Stop).Id 
}
catch {

    $exceptionMessage = $Error[0].Exception.Message.Split("-")[1].Trim()
    
    Write-Warning "Error: $exceptionMessage, at $logLocation`n"
}

Throw Exception

function Get-LoggedInUserObjectId {

	$account = (Get-AzContext).Account
	
	if(!$account){
		throw "Could not get logged in user account information"
	}
	
    return (Get-AzADUser -UserPrincipalName $account).Id
}

Custom Exception Class

#
# Coutesy: https://stackoverflow.com/a/66349347/4802664
#

class CustomException : Exception {

    [string] $additionalData

    CustomException($Message, $additionalData) : base($Message) {
        $this.additionalData = $additionalData
    }
}

try {

    throw [CustomException]::new('Error message', 'Extra data')
	
} catch [CustomException] {

    # NOTE: To access your custom exception you must use $_.Exception
    Write-Output $_.Exception.additionalData

    # This will produce the error message: Didn't catch it the second time
    throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}