php language basics

Errors and Exceptions Basics

Errors and exceptions are how PHP tells you something went wrong. A syntax error means PHP could not understand the code. A warning or notice usually means the code ran into a suspicious situation. An exception is an object thrown by code to say "this path cannot continue normally."

As a beginner, focus on three habits: fail early when input is invalid, catch exceptions only where you can do something useful, and do not show raw error details to users in production.

Throwing For Invalid Input

Use an exception when a function cannot do its job with the value it received.

PHP example
<?php

function normaliseName(string $name): string
{
    $name = trim($name);

    if ($name === '') {
        throw new InvalidArgumentException('Name is required.');
    }

    return $name;
}

echo normaliseName(' Ada ') . "\n";

// Prints:
// Ada

The function rejects an empty name before returning a value. That is better than letting empty data move deeper into the application and cause a harder bug later.

Catching An Exception

Use try and catch when you want to handle an exception and continue with a controlled response.

PHP example
<?php

function normaliseName(string $name): string
{
    $name = trim($name);

    if ($name === '') {
        throw new InvalidArgumentException('Name is required.');
    }

    return $name;
}

try {
    echo normaliseName('   ') . "\n";
} catch (InvalidArgumentException $exception) {
    echo "Please enter your name.\n";
}

// Prints:
// Please enter your name.

The user-facing message is simple. The exception message can be useful for logs or debugging, but you usually do not show internal details directly to users.

Catch Specific Exceptions First

Catch the specific exception type you expect. Catching every Throwable too early can hide programming mistakes.

PHP example
<?php

function parsePositiveAmount(string $value): int
{
    if (!ctype_digit($value)) {
        throw new InvalidArgumentException('Amount must contain digits only.');
    }

    $amount = (int) $value;

    if ($amount <= 0) {
        throw new InvalidArgumentException('Amount must be positive.');
    }

    return $amount;
}

try {
    echo parsePositiveAmount('25') . "\n";
} catch (InvalidArgumentException $exception) {
    echo "Invalid amount.\n";
}

// Prints:
// 25

This function treats invalid input as an expected failure path. It still returns a normal integer when the input is valid.

Warnings Are Not A Plan

Do not rely on PHP warnings as validation. Check the data before using it.

PHP example
<?php

$payload = ['email' => 'amo@example.com'];

if (!isset($payload['name'])) {
    echo "Name is missing\n";
    return;
}

echo $payload['name'] . "\n";

// Prints:
// Name is missing

The code checks the key before reading it. That makes the failure path deliberate instead of letting PHP warn about a missing array key.

Development And Production

During development, visible errors help you fix code quickly. In production, raw errors can leak paths, SQL details, tokens, configuration names, and other sensitive information.

Production applications should log errors for developers and show users a safe message. The exact logging setup comes later, but the habit starts here: error details are for developers, not for public output.

Common Mistakes

Do not catch an exception and ignore it. If the failure matters, handle it or let it keep moving upward.

Do not throw exceptions for ordinary branches such as "order is pending" when a return value would be clearer.

Do not expose exception messages from low-level code directly to users. Convert them to safe user-facing messages at the boundary.

What You Should Be Able To Do

After this lesson, you should be able to:

  • throw InvalidArgumentException for invalid function input;
  • catch an expected exception with try and catch;
  • explain the difference between a normal branch and an exceptional failure;
  • check array keys before reading them;
  • avoid showing raw error details to users.

Practice

Task: Reject Empty Name

Task

Write a function named normaliseName() that accepts a string and returns the trimmed name.

The function should:

  • trim surrounding spaces;
  • throw InvalidArgumentException if the trimmed name is empty;
  • return the cleaned name otherwise.

Call it with ' Mina ' and print the result.

Hints

  • Use trim().
  • Check for an empty string after trimming.
  • Throw before returning.
Show solution

Solution

PHP example
<?php

function normaliseName(string $name): string
{
    $name = trim($name);

    if ($name === '') {
        throw new InvalidArgumentException('Name is required.');
    }

    return $name;
}

echo normaliseName(' Mina ') . "\n";

// Prints:
// Mina

Explanation

The function checks the cleaned value, not the original value. A string containing only spaces becomes empty after trim(), so it should be rejected.

Task: Predict Exception Path

Task

Before running this code, predict what it prints.

PHP example
<?php

function requirePositiveQuantity(int $quantity): int
{
    if ($quantity <= 0) {
        throw new InvalidArgumentException('Quantity must be positive.');
    }

    return $quantity;
}

try {
    echo requirePositiveQuantity(0) . "\n";
    echo "Accepted\n";
} catch (InvalidArgumentException $exception) {
    echo "Invalid quantity\n";
}

Then run the code and compare the output with your prediction.

Hints

  • Code after the throwing line inside the try block does not keep running.
  • The matching catch block handles the exception.
Show solution

Solution

PHP example
<?php

function requirePositiveQuantity(int $quantity): int
{
    if ($quantity <= 0) {
        throw new InvalidArgumentException('Quantity must be positive.');
    }

    return $quantity;
}

try {
    echo requirePositiveQuantity(0) . "\n";
    echo "Accepted\n";
} catch (InvalidArgumentException $exception) {
    echo "Invalid quantity\n";
}

// Prints:
// Invalid quantity

Explanation

requirePositiveQuantity(0) throws an exception. PHP leaves the try block immediately, so Accepted is not printed. The catch block handles the InvalidArgumentException.

Task: Handle Invalid Amount

Task

Write a function named parsePositiveAmount() that accepts a string and returns a positive integer amount.

The function should:

  • throw InvalidArgumentException if the string contains anything other than digits;
  • throw InvalidArgumentException if the parsed amount is 0;
  • return the amount otherwise.

Call it inside a try block with '0'. Catch InvalidArgumentException and print Invalid amount.

Hints

  • Use ctype_digit() for the digit check.
  • Convert with (int) after checking the string.
  • Keep the user-facing error message simple.
Show solution

Solution

PHP example
<?php

function parsePositiveAmount(string $value): int
{
    if (!ctype_digit($value)) {
        throw new InvalidArgumentException('Amount must contain digits only.');
    }

    $amount = (int) $value;

    if ($amount <= 0) {
        throw new InvalidArgumentException('Amount must be positive.');
    }

    return $amount;
}

try {
    echo parsePositiveAmount('0') . "\n";
} catch (InvalidArgumentException $exception) {
    echo "Invalid amount\n";
}

// Prints:
// Invalid amount

Explanation

The function rejects bad input with exceptions. The caller catches the expected validation failure and prints a safe user-facing message instead of exposing the internal exception text.