J
J
JackShcherbakov2018-01-28 16:49:46
PHP
JackShcherbakov, 2018-01-28 16:49:46

Why can't I catch an error in PHP?

Hello! I'm learning php on the 4th day by David Sklyar's book. I got to classes and error indication and decided to write this code:

$usersCount= 0;
class User{

  public $name;
  public $age;
  public function __construct($name, $age){
    if($age>=100){
      throw new Exception('$age must be <100');
    }
    $this->age = $age;
    $this->name = $name;
    $GLOBALS[usersCount]+=1;
  }
  public function showAge(){
    print "Возвраст пользователя $this->name - $this->age<br>";
    
  }

  public static function showUsersCount(){
    print "Количество пользователей - $GLOBALS[usersCount]<br>";
  }

}
try{
  $bob = new User("Боб", 34);
  $bob->showAge();

  $jack = new User("Джек", 42);
  $jack->showAge();

  $maria = new User("Мария", 23);
  $maria->showAge();

  $mikle = new User("Майкл", 1312);
  $mikle->showAge();
}catch(Exeption $e){
  print "Error: " . $e->getMessage();
}
User::showUsersCount();

If the user's return is greater than 100, then we throw an error that will be caught in the level above. But for some reason, the error arrives immediately to the interpreter, and catch does nothing, although according to the plan, it should only print an error message via print.
Here is what is displayed in the browser:
User Bob return - 34
User Jack return - 42
User Maria return - 23
Fatal error: Uncaught Exception: $age must be <100 in C:\OpenServer\domains\asd\Untitled_1.php:45 Stack trace: #0 C:\ OpenServer\domains\asd\Untitled_1.php(71): User->__construct('\xD0\x9C\xD0\xB0\xD0\xB9\xD0\xBA\xD0\xBB', 1312) #1 {main} thrown in C:\OpenServer\domains\asd\Untitled_1.php on line 45

And it should be something like this:

User Bob's age is 34
Jack's age is 42
Mary's age is 23
Error: $age must be <100

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
JackShcherbakov, 2018-01-28
@JackShcherbakov

Solution found! Error here
Should be:

<code>
/*...*/catch(Exception $e)/*...*/
</code>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question