NullReferenceException for OverlapSphere

Im using overlapSphere to get targets for AI, but if there is no targets - i got exception (NullReferenceException), i know, thats ok, no target - no return. But that is so annoying to see tons of this exceptions in console. Is there any way to fix it? Code here.

Error:

NullReferenceException: Object reference not set to an instance of an object
ShellScript.OnCollisionEnter (UnityEngine.Collision collider) (at Assets/Scripts/ShellScript.cs:33)

using System.Collections;
using System.Linq;
using UnityEngine;


public class GunTurret : MonoBehaviour
{

    public Animation anim;
    Collider curTarget;
    public GameObject Shell;
    public GameObject Stvol;
    public float maxAttackDistance = 20.0f;
    public float minAttackDistance = 5f;
    public static GameObject shootObject;
    GameObject nearestmob;
    GameObject temp;
    GameObject temp2;
    bool canFire = true;
    public float RotationSpeed =5;
    float maxHP = 100; 
    float curHP = 100;
    public float incDamage;
    private GlobalVars gv;

    void Start()
    {
    
    }

    private void Update()
    {
        takeDamage();
        SortTargets();
        if (curTarget == null)
        {
            randomIdle();
            SortTargets();
            curTarget = nearestmob.collider;
        }
        else
            Targeting();
    }

    void Targeting()
    {
        float distance = Vector3.Distance(transform.position, curTarget.transform.position);
        var targetRotation = Quaternion.LookRotation((curTarget.transform.position) - transform.position);
            if (distance < maxAttackDistance && distance > minAttackDistance)
            {
                transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, RotationSpeed * Time.deltaTime);
                if (Vector3.Angle(transform.forward, curTarget.transform.position - transform.position) < 20)
                    if (canFire)
                      StartCoroutine(fire());
            }
            else
                curTarget = null;
    }

        private Collider SortTargets()
        {
            var minDist = minAttackDistance*minAttackDistance;
            var turretPosition = this.transform.position;
            //Debug.Log("scan");
            Collider[] cols = Physics.OverlapSphere(turretPosition, maxAttackDistance);
            float closestMobDistance =0.0f;
            foreach (Collider col in cols)
            {
                if (col.tag == "Monster")
                {
                    var dist = ((col.transform.position - turretPosition).sqrMagnitude);
                    if (dist > minDist)
                    {
                        if ((dist < closestMobDistance) || (closestMobDistance == 0))
                        {
                            closestMobDistance = dist;
                            nearestmob = col.gameObject.gameObject;
                        }
                    }
                }
            }
            if (nearestmob != null)
                return nearestmob.collider;
            else
                return null;
        }

    void randomIdle()
    {
       // Debug.Log("idle");

        var x = Random.Range(1, 3);
        if (x==1)
            anim.CrossFadeQueued("idle1");
        if (x==2)
            anim.CrossFadeQueued("idle2");
        if (x == 3)
            anim.CrossFadeQueued("idle3");
        
    }

    private IEnumerator fire()
    {

            {
                anim.CrossFade("fire");
                canFire = false;
                yield return new WaitForSeconds(0.9f);
                Instantiate(Shell, Stvol.transform.position, Quaternion.LookRotation(curTarget.transform.position - transform.position));
                StartCoroutine(reload());
            }
    }

    IEnumerator reload()
    {

        anim.CrossFade("reload");
        yield return new WaitForSeconds(5.0f);
        canFire = true;
    }

    private void takeDamage()
    {

        curHP -= incDamage;
        incDamage = 0;
        if (curHP <= 0) 
        Destroy(gameObject); 
    }

    private void OnDestroy()
    {
        if (gv != null)
        {
            gv.TurretList.Remove(gameObject);
            gv.TurretCount--;
        }
    }
}

Hi mate!

I’m almost sure that when you return at line 23, you want to return the nearest collider, but if you list is empty, the nearest is null then KABOUM! =D

Just add a null check condition before returning and the bug will be fixed.

Good luck.

Edit:
Line 23:

if (nearestmob != null) // If your list is empty, nearestmob won't be set. That's why it can raise an exception.
    return nearestmob.collider;
else
    return null;

The foreach loop should be skipped without any error case the array returned by OverlapSphere was empty. I can think of two possibilities:

1- Maybe OverlapSphere returns null instead of an empty array when there’s no collider: if this is the case, verify the array before the foreach:

        if (cols) foreach (Collider col in cols)
        {

2- The array returned by OverlapSphere should not contain any null element, but the example in the docs tests for a null collider in the array - include this test in your loop like this:

        foreach (Collider col in cols)
        {
            if (!col) continue; // skip null colliders
            if (col.tag == "Monster")
            {