</>
Skip to content
PHP lessons (24/49)

PHP — Form Handling

Basic try-catch

<?php
try {
    $result = 10 / 0;
} catch (DivisionByZeroError $e) {
    echo "Error: " . $e->getMessage();
}
?>

Custom exceptions

<?php
class InsufficientFundsException extends Exception {
    public function __construct(float $amount) {
        parent::__construct("Insufficient funds: need $amount");
    }
}

class BankAccount {
    private float $balance;

    public function __construct(float $initial) {
        $this->balance = $initial;
    }

    public function withdraw(float $amount): void {
        if ($amount > $this->balance) {
            throw new InsufficientFundsException($amount - $this->balance);
        }
        $this->balance -= $amount;
    }
}

try {
    $acc = new BankAccount(100);
    $acc->withdraw(150);
} catch (InsufficientFundsException $e) {
    echo $e->getMessage();
}
?>

Multiple catch blocks

<?php
try {
    $data = json_decode("invalid", true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception("JSON error");
    }
} catch (TypeError $e) {
    echo "Type error: " . $e->getMessage();
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
} finally {
    echo "Cleanup";
}
?>

Finally block

<?php
function readConfig(string $path): array {
    $file = null;
    try {
        $file = fopen($path, 'r');
        return json_decode(fread($file, filesize($path)), true);
    } catch (Exception $e) {
        return [];
    } finally {
        if ($file) fclose($file);
    }
}
?>

Exception chaining

<?php
try {
    try {
        throw new Exception("Original error");
    } catch (Exception $e) {
        throw new Exception("Wrapper error", 0, $e);
    }
} catch (Exception $e) {
    echo $e->getMessage();
    echo $e->getPrevious()->getMessage();
}
?>

Mini Practice

Write PHP code that:

  1. Creates a custom exception
  2. Uses try-catch-finally
  3. Chains exceptions
  4. Handles multiple exception types

Up Next

In the next lesson, you'll learn about File Handling — reading and writing files.

Related Topics

Frequently Asked Questions about Form Handling

What is Form Handling in PHP?

Form Handling is a fundamental concept in PHP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Form Handling?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Form Handling.

Why is Form Handling important in PHP?

Form Handling is essential for PHP development. Understanding this concept will help you write better code and solve real-world problems more effectively.