Exception Handling in Windows PowerShell

 

Simple Try/Catch/Finally

try{
Write-Host program started;
$a="abcd";
$a=$a.add(12);
}catch{
Write-Host some exception occured;
}finally{
Write-Host inside finally block;
}
The above program wont run as it is using some method that has not been defined. So due to exception it prints the statement "some exception occured". After this the finally block is executed and the program ends.
But what sorts of exception were encountered in the program is still unknown. Either we need to handle individual exception by knowing the exception type or need to trace out the whole exception log.

These can be some possible catch blocks:
try{
#some code block to cause the exception in catch block 
}catch [System.Net.Sockets.SocketException] {
        return New-Object PSObject -Property @{
            Pass=$false;
            Exception=[string]::Format("Socket exception: {0}", $_);
        }        
    }
    catch [System.ObjectDisposedException] {
        return New-Object PSObject -Property @{
            Pass=$false;
            Exception="TcpClient is closed";
        }
    }
    catch {
        return New-Object PSObject -Property @{
            Pass=$false;
            Exception="Unhandled Error";
        }    
    }
 
But when we dont know what was the cause then it can be helpful to parse the exception trace.
 

Printing Stack Trace

#Get detailed information on an error
function Resolve-Error ()
{
   $ErrorRecord=$Error[0];
   $ErrorRecord | Format-List * -Force;
   $ErrorRecord.InvocationInfo |Format-List *;
   $Exception = $ErrorRecord.Exception;
   for ($i = 0; $Exception; $i++, ($Exception = $Exception.InnerException))
   {   "$i" * 80;
       $Exception |Format-List * -Force;
   }
}

No comments:

Post a Comment