2

Hi devs

I have a simple PHP OO project. I have an exception who appears 2 times. Something like :

if (!$x) {
    throw new Exception("Don't use this class here.");
}

I want to dev a class in order to edit this code like that :

if (!$x) {
    throw new ClassUsageException();
}

How to dev the Excpetion class with default Exception message ?

Thanks

1
  • which framework are you using? Commented Mar 2, 2016 at 13:51

2 Answers 2

1

I'd advise creating new exception classes sparsly. It is no fun to check a multitude of exceptions left and right. And if you really feel the need, check what kinds of exceptions are already defined and where in that hierarchy your exception will fit and then extend that class, i.e. give the developers a chance to catch a (meaningful) range of exceptions without having to explicitly write one catch-block after the other.

I'm really not sure what you're trying to achieve here with Don't use this class here. but it could be an InvalidArgumentException (or something derived from that exception, if you really must). There are other mechanisms to prevent an instance of a certain class at a specific place though.

Sign up to request clarification or add additional context in comments.

Comments

0

You can extend the Exception class

<?php
Class ClassUsageException extends Exception {

    public function __construct($msg = "Don't use this class here.", $code = 0) {
         parent::__construct($msg, $code); //Construct the parent thus Exception.
    }

}


try {
    throw new ClassUsageException();
} catch(ClassUsageException $e) {
   echo $e->getMessage(); //Returns Don't use this class here.
}

4 Comments

I guess that the message should be already a default one, as in the question: with default Exception message. So maybe in the constructor: __construct($msg = 'the default message here', $code =0){.... This would still allow the OP to change the message, anyway...
@FirstOne In that case, changed it.
Just note that I'm not the OP, that just my understanding of the question ^^
@FirstOne You're right, I read the question too fast, thanks for commenting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.