Often we need to retrieve SPList instance from SPWeb by title or server relative URL. We can do it using the following code:
But the problem is that if list not found these methods have different behaviors: indexer SPWeb.Lists[…] throws System.ArgumentException (“Value does not fall within the expected range”) and SPWeb.GetList(…) method throws System.IO.FileNotFoundException (“The system cannot find the file specified. (Exception from HRESULT: 0x80070002)”). So in order to handle such errors we need to add try/catch with different catch blocks in our code. This is not very convenient.
In order to simplify error handling and make it similar for both cases I wrote 2 simple extension methods for SPWeb class:
Instead of throwing exceptions these methods will return null. So you don’t need to add try/catch every time you retrieve list from SPWeb – you just need to check it on null after it was safely retrieved:
And if you will decide to retrieve list by URL instead of title you will not need to change your error handling logic – it will remain the same.