How can try-catch blocks be effectively used to handle errors when using eval() in PHP?

When using eval() in PHP, errors can occur if the evaluated code contains syntax errors or generates runtime errors. To handle these errors effectively, try-catch blocks can be used to catch and handle exceptions that may be thrown during the evaluation of the code. By wrapping the eval() function call in a try block and catching any potential exceptions in a catch block, you can gracefully handle errors and prevent them from crashing the script.

try {
    eval($code);
} catch (Throwable $e) {
    echo 'An error occurred: ' . $e->getMessage();
}