DEV Community

Ghulam Mujtaba
Ghulam Mujtaba

Posted on

Exception in OOP php

Exception

In OOP PHP, an exception is an object that represents an error or unexpected behavior in a program. It's a way to handle and manage errors in a more structured and organized way.

Purpose

The purpose of exceptions is to:

  • Separate error handling code from regular code
  • Provide a way to handle errors in a centralized and reusable way
  • Allow for more informative and specific error messages

How to Use Exceptions

  • Try: Wrap code that might throw an exception in a try block.

  • Throw: Use the throw keyword to create and throw an exception.

  • Catch: Use a catch block to handle an exception.

An example related to exception is:

<?php 

class TeamException extends Exception {
    public static function fromTooManyMembers() {
        return new static('You may not add more than 3 team members.');
    }
}

class Member {
    public $name;
    public function __construct($name) {
        $this->name = $name;
    }
}

class Team {
    protected $members = [];
    public function add(Member $member) {
        if(count($this->members) === 3){
            throw TeamException::fromTooManyMembers();
        }
        $this->members[] = $member;
    }
    public function members() {
        return $this->members;
    }
}

class TeamMembersController {
    public function store() {
        $team = new Team;
        try{
            $team->add(new Member('John Doe'));
            $team->add(new Member('Ghulam Mujtaba'));
            $team->add(new Member('Ali Hassan'));
            $team->add(new Member('Ahmad Ali'));
            var_dump($team->members());
        } catch(TeamException $e ) {
            var_dump($e -> get message());
        }
    }
}

(new TeamMembersController())->store();
Enter fullscreen mode Exit fullscreen mode

In this code snippet, we have a TeamException class that extends the built-in Exception class. This custom exception is used to represent an error when trying to add more than 3 members to a team.

When we run this code, it will output the exception object with the error message "You may not add more than 3 team members." This demonstrates how exceptions can be used to handle errors in a more structured and informative way.

I hope that you have clearly understood it.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.