Search⌘ K
AI Features

Solution Review: Exception Handling

Explore how to effectively manage exceptions in PHP OOP by creating classes with validation methods that throw exceptions for invalid input. Understand handling errors gracefully during user data processing and testing to build reliable PHP applications.

We'll cover the following...

Solution

PHP
<?php
class User {
private $name;
private $age;
public function setName($name) {
$name = trim($name);
if(strlen($name) < 3) {
throw new Exception("The name should be at least 3 characters long");
}
$this -> name = $name;
}
public function setAge($age) {
$age = (int)$age;
if($age < 1) {
throw new Exception("The age cannot be zero or less");
}
$this -> age = $age;
}
public function getName() {
return $this -> name;
}
public function getAge() {
return $this -> age;
}
}
function test()
{
$dataForUsers = array(
array("Ben",4),
array("Eva",28),
array("li",29),
array("Catie","not yet born"),
array("Sue",1.5)
);
foreach($dataForUsers as $data => $value) {
try
{
$user = new User();
$user -> setName($value[0]);
$user -> setAge($value[1]);
echo $user -> getName() . " is " . $user -> getAge() . " years old\n";
}
catch (Exception $e)
{
echo "Error: " . $e -> getMessage() . " in the file: " . $e -> getFile() . "\n";
}
}
}
echo test();
?>

Explanation

  • Lines 2–4: We create a User class with two private properties, $name and $age.
...