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

Catch Exception


# Catch generic exception
try {
    # ... ... ...
}
catch {
	
	$errorMessage = $Error[0] # $Error is a magic variable -> catches errors
	
	Write-Error "Error occured -> ErrorMessage: $errorMessage"
	
    return
}

# Catch specific exception
try {
    # ... ... ...
}
catch [Xxx]{
	
	$errorMessage = $Error[0] # $Error is a magic variable -> catches errors
	
	Write-Error "Error occured -> ErrorMessage: $errorMessage"
	
    return
}

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')
}