How to make this code valid only when the value exists?

If we refer to the documentation, we see that get_the_terms returns an array, false, or a WP_Error object. So in our code we’ll add a check if $collection_values exists (it’s not false), and it’s not an error, then we’ll know it has to be an array, and it’s safe to run a foreach loop on it.

$collection_values = get_the_terms( $product->id, 'pa_collection');

if ( $collection_values && ! is_wp_error( $collection_values ) ){
    foreach ($collection_values as $collection_value){
        echo '<h2 class="collection_title"><a href="'.get_term_link($collection_value->slug, $collection_value->taxonomy).'">'.$collection_value->name.'</a></h2>';
    }
}