...

/

Solution Review: Exception Handling

Solution Review: Exception Handling

Let's look at the solution of the Exception Handling challenge.

We'll cover the following...

Solution

Press + to interact
<?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

...