Learn
← Previous Next →

Hari 13: Error Handling & Exception

60 min Last updated 09 Apr 2026

Try / Catch / Finally

function bagi(float $a, float $b): float {
    if ($b === 0.0) {
        throw new InvalidArgumentException("Pembagi tidak boleh nol!");
    }
    return $a / $b;
}

try {
    echo bagi(10, 2) . "\n";  // 5
    echo bagi(5, 0) . "\n";   // throw exception
} catch (InvalidArgumentException $e) {
    echo "Error: " . $e->getMessage() . "\n";
} catch (Exception $e) {
    echo "General error: " . $e->getMessage() . "\n";
} finally {
    echo "Selesai!\n"; // selalu jalan
}

Custom Exception

class NilaiTidakValidException extends Exception {
    public function __construct(private float $nilai) {
        parent::__construct("Nilai $nilai di luar rentang 0-100");
    }

    public function getNilai(): float { return $this->nilai; }
}

function validasi_nilai(float $nilai): string {
    if ($nilai < 0 || $nilai > 100) {
        throw new NilaiTidakValidException($nilai);
    }
    return $nilai >= 60 ? "Lulus" : "Tidak Lulus";
}

try {
    echo validasi_nilai(85) . "\n";   // Lulus
    echo validasi_nilai(150) . "\n";  // throw
} catch (NilaiTidakValidException $e) {
    echo $e->getMessage() . "\n";     // Nilai 150 di luar rentang 0-100
}

💡 Notice: PHP 8+ mendukung throw sebagai ekspresi (bisa dipakai di dalam match dan ternary).

Assignment

Buat fungsi konversi_suhu(float $c, string $ke) yang konversi Celsius ke "F" (fahrenheit) atau "K" (kelvin). Jika $ke bukan F atau K, throw InvalidArgumentException. Tampilkan hasil konversi 100C ke F, dan tangkap exception untuk satuan "X".

Expected output:

212
Error: Satuan tidak dikenal: X
PHP index.php
Solution
Output