Bird
0
0

How can you add a custom property $errorCode to a custom exception class and access it after catching?

hard📝 Application Q9 of 15
PHP - Error and Exception Handling

How can you add a custom property $errorCode to a custom exception class and access it after catching?

class MyException extends Exception {
  private int $errorCode;

  public function __construct(string $message, int $code) {
    parent::__construct($message);
    $this->errorCode = $code;
  }

  public function getErrorCode(): int {
    return $this->errorCode;
  }
}

try {
  throw new MyException("Failed", 404);
} catch (MyException $e) {
  // What to echo here?
}
Aecho $e->getErrorCode();
Becho $e->errorCode;
Cecho $e->code;
Decho $e->getCode();
Step-by-Step Solution
Solution:
  1. Step 1: Identify how errorCode is stored

    The property $errorCode is private and accessed via getErrorCode() method.
  2. Step 2: Check options for accessing errorCode

    Only echo $e->getErrorCode(); correctly accesses the private property via its getter.
  3. Final Answer:

    echo $e->getErrorCode(); -> Option A
  4. Quick Check:

    Access private property via getter method [OK]
Quick Trick: Use getter methods to access private exception properties [OK]
Common Mistakes:
  • Trying to access private property directly
  • Using built-in getCode() instead of custom property
  • Confusing property names

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes