What is an exception? How to use it! ?

Aug 28, 2020 PHP exception Exception handling Try-Catch

Do you use exception handling?

Exception handling that appears in programming explanations. Somehow I understood the mechanism, but it is difficult to actually use it.

** It works even if you don’t use it! **

** It’s a hassle to write try-catch or Exception! **

At first I didn’t know how to use it, but While looking at other code and studying, I found out that “I can write better code by using exception handling”.

So, let’s summarize when to use exception handling.

*I will explain using the PHP language, but I think the exception handling is basically the same.

Function to calculate change

Implement the function that calculates the fishing by passing the product price $price and the payment amount $payment. However, there may be cases where payments are small relative to the product price.

function calChange(int $price, int $payment): int
{
    return $payment-$price;
}

$change1 = calChange(900, 1000); // 100
$change2 = calChange(1000, 900); // -100

The calculation now looks like this. But what about the case where the payment is small? In that case, you can not purchase the item in the first place, so you can not calculate the change.

It seems like you can decide that “If the return value is negative, the payment amount is insufficient”, but the judgment of >= 0 will be followed.

Bad example

function calChange(int $price, int $payment): array
{
    $change = $payment-$price;
    return [
        'result' => ($change >= 0),
        'change' => $change,
    ];
}

$result1 = calChange(900, 1000); // ['result' => true,'change' => 100]
$result2 = calChange(1000, 900); // ['result' => false,'change' => -100]

It is a pattern that makes the return value an array and packs various information. At first glance it is easy, but sometimes the information becomes large and complicated. The return value should be simple.

Example using an exception

function calChange(int $price, int $payment): int
{
    $change = $payment-$price;

    if ($change <0) {
        throw new \Exception('Payment is insufficient');
    }

    return $change;
}

try {
    $change1 = calChange(900, 1000); // 100
    $change2 = calChange(1000, 900); // Throw Exception
} catch (\Exception $e) {
    echo $e->getMessage(); // insufficient payment
}

In cases where the payment amount is insufficient, the exception is throw. In this implementation, the return value is guaranteed to be 0 or more, so the normal system is a simple flow.

How to handle throw exceptions? About is left to the side using the function. For example, processing such as returning to the form as an input error or displaying the screen of the system error will be performed. It’s just an exception in the function calChange(), and whether it’s critical to the whole or not is another matter.

I want to know how much is lacking

Let’s extend the exception. Create NotEnoughPaymentException and have the information of the insufficient amount.

class NotEnoughPaymentException extends \Exception
{
    protected $shortage;

    public function __construct(int $shortage, $message = null, $code = 0, Exception $previous = null)
    {
        $this->shortage = $shortage;
        parent::__construct($message, $code, $previous);
    }

    public function getShortage(): int
    {
        return $this->shortage;
    }
}
function calChange(int $price, int $payment): int
{
    $change = $payment-$price;

    if ($change <0) {
        throw new NotEnoughPaymentException(
            $change * -1,
            'Insufficient payment');
    }

    return $change;
}

try {
    $change = calChange(1000, 900); // Throw NotEnoughPaymentException
} catch (NotEnoughPaymentException $e) {
    echo $e->getShortage() .'The yen is insufficient. '; // 100 yen is running out.
}

#Summary

The description so far is just an example. “What to make an exception” depends on what role the function calChange() has.

The important thing is to make it clear what you do.

We hope you find it useful as a reference for exception handling.

bonus

throw new \Exception();

This is often explained as an example, but throw and new are not a set. Breaking down the above example would be:

$e = new \Exception();
throw $e;

If you want to throw the catch exception as it is, it will be as follows.

try {
    throw new \Exception('is an exception');
} catch (\Exception $e) {
    throw $e;

    // you don't have to do this
    // throw new \Excepton($e->getMessage());
}