Exception Handling

Error handling is necessary while writing code. Usually we check and validate conditions for expected bevaviour, but sometimes unexpected behaviour causes application crashing issues. So to handle any upexpected thing, scripting languages or programming languages introduce Error handling usually it is called Exception handling.

Let's look how exceptions can be raised and how it can be handled.

Few important keywords are there to handle exceptions e.g. Exception, try, catch, finally. Let's undertand Exception Handling with an example.

Example
function getPercentage($totalMarks, $totalSubject)
{
    return $totalMarks / $totalSubject;
}

$percentage = getPercentage 480 5;

$percentage;

Above function will show 96. Now, if you pass 0 as a 2nd parameter, it will show Error as below.

Example
$percentage = getPercentage 480 0;

$percentage;

Attempted to divide by zero.
At line:3 char:12
+     return $totalMarks / $totalSubject;
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException

Instead of showing system message you would like to show user friendly message. To show user friendly message you need to handle exception using "Try" and "Catch" keywords.

Example
function getPercentage($totalMarks, $totalSubject)
{
    try
    {
        return $totalMarks / $totalSubject;
        
    }
    catch [System.DivideByZeroException]
    {
        Write-Host "Any value can't devide by zero, please pass another value for totalSubject";
    }
    catch [System.Exception]
    {
        Write-Host "Something has gone wrong";
    }
    finally
    {
        Write-Host "This will be executed everytime";
    }
}

$percentage = getPercentage 480 5;

$percentage;

Now run above code and you will not see any error there, instead you will see message what you want to print and user can understand easily what user has done wrong here. Also, please notice that we have used multiple catch statements for different types of error. So if there any specific type of error has been thrown then that will be caught in specific catch, but if related catch block is not written then exception will be caught in last catch "System.Exception". Also, we have written "finally" block, finally block will be executed always doent's matter if any exception would be thrown inside of try block or not.

 

← Previous

Next →