Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine which exceptions "x[]" might throw?

C# reference for square brackets says: Square brackets [] are used for arrays, indexers, and attributes. They can also be used with pointers. (It also says, for arrays) An exception is thrown if an array index is out of range.

So when you're using square brackets on something other than an array, how do you know what exceptions might be thrown?

For a Dictionary (for example) if you use accessor methods such as Dictionary.TryGetValue you can easily look up the exceptions that the method may throw, but the C# reference for square brackets [] only says it may throw an exception for index out of range on arrays.

So if you want to use the square brackets for some data type, where can you lookup which exceptions might be thrown for that data type?

I tried accessing a nonexistent member of a Dictionary, just to see what happens, and I got KeyNotFoundException. I know you can also get NullReferenceException. Where is this documented? And what's the complete list?

like image 337
Edward Ned Harvey Avatar asked Feb 20 '13 22:02

Edward Ned Harvey


1 Answers

It's documented with each implementation. There's not an exhaustive list as the operator can be overloaded, so thoeretically any exception could be thrown. The operator is typically documented as an Item property.

Here's some documentation on specific uses:

Dictionary.Item

Array.Item

However, you should not need an exhaustive list on what could be thrown. Exceptions are typically caught for one of two reasons: either you want to do something about it (like the days before TryParse when catching an exception was the simplest way to catch a bad date format) or you just want to note that an exception occured and log it, in which case you typically rethow the actual exception.

Catching specific exceptions is good for the former case. For example if you catch a NullReferenceException it's typically to re-throw a different exception that indicates which reference is null (since this is not part of the stock NullReferenceException).

In the latter case, Catching a generic Exception is fine if you just want to log and re-throw since there's likely nothing else you can do about it.

like image 99
D Stanley Avatar answered Sep 22 '22 19:09

D Stanley