Sobes.tech
Junior — Middle

Do you have experience writing custom exceptions in code?

sobes.tech AI

Answer from AI

Yes, I have experience writing custom exceptions in PHP. Creating user-defined exceptions helps to better structure error handling and make the code more readable and maintainable.

To create a custom exception, you need to define a class that extends the built-in Exception class or its descendants.

Example of a custom exception in PHP:

<?php
class MyCustomException extends Exception {
    public function errorMessage() {
        // Custom error message
        return "Error in MyCustomException class: " . $this->getMessage();
    }
}

try {
    // Some logic that might throw an exception
    throw new MyCustomException("Something went wrong");
} catch (MyCustomException $e) {
    echo $e->errorMessage();
}
?>

This approach allows creating exceptions with additional logic and using them for more precise error control.