What best practices should be followed when handling exceptions and namespaces in PHP code to avoid conflicts?

When handling exceptions and namespaces in PHP code, it is important to use specific namespaces for exceptions to avoid conflicts with other classes or libraries. This can be achieved by creating custom exception classes within a dedicated namespace. Additionally, it is recommended to use fully qualified names when referencing exception classes to ensure the correct class is used.

<?php

namespace MyNamespace;

// Custom exception class within a dedicated namespace
class CustomException extends \Exception {
    // Custom exception code
}

try {
    // Code that may throw an exception
    throw new CustomException('An error occurred.');
} catch (\MyNamespace\CustomException $e) {
    // Handle the custom exception
    echo 'Caught exception: ' . $e->getMessage();
}