How can one efficiently handle errors or exceptions when converting decimal to binary in PHP?

When converting a decimal number to binary in PHP, errors or exceptions may occur if the input is not a valid decimal number. To efficiently handle these errors, you can use PHP's built-in functions like is_numeric() to check if the input is a valid number before converting it to binary. If the input is not valid, you can throw an exception or return an error message.

function decimalToBinary($decimal) {
    if (!is_numeric($decimal)) {
        throw new Exception("Invalid input. Please provide a valid decimal number.");
    }
    
    return decbin($decimal);
}

try {
    $decimal = 10;
    echo decimalToBinary($decimal);
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}