0

Is it bad style and/or bad for performance to write code that you know might fail and ignore the exception? For example (in C#):

long l = 1;
try {
  l = (long)castObject;
} catch(InvalidCastException e) { }

In this scenario, the programmer doesn't particularly care whether or not an InvalidCastException is thrown.

drew.cuthbert
  • 1,005
  • 1
  • 9
  • 21
  • I generally try to avoid swallowing exceptions as that's a bad practice to get into, even if it may not seem to be an issue in a particular instance. – Tim Sep 19 '14 at 02:37
  • 2
    Why not `long? v = castObject as long?; if (v.HasValue) l = v.Value;`? – Mephy Sep 19 '14 at 02:37
  • @Tim you can't `as` to a value type like `long`, needs `long?` or `Nullable` instead. – Mephy Sep 19 '14 at 02:38
  • 3
    @Mephy: Note http://stackoverflow.com/q/1583050/34397 – SLaks Sep 19 '14 at 02:40
  • Side note: likely the problem is not in that piece of code , but rather in other code that uses non-generic collections or some other code that ignores type of objects... (in any case if you need to ignore particular exception you should catch just that exception) – Alexei Levenkov Sep 19 '14 at 02:46
  • @Mephy thanks for the info, I didn't know about using `?` for nullable types like that. @SLaks very good to know, thanks. – drew.cuthbert Sep 19 '14 at 02:47

1 Answers1

6

Don't do that.

  • Exceptions incur a substantial performance hit.
  • It will annoy developers who run with Break On Exceptions turned on.
    (which you should do to catch hidden bugs)
  • It makes the intent less clear. (why might it not be a long?)
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 3
    In addition to the above, the `catch` can catch stuff that you probably don't want to hide, such as `OutOfMemoryException`, `Exception` and `StackOverflowException`. – Sam Sep 19 '14 at 02:45
  • 2
    @Sam no, that's not correct as StackOverflowException cannot be caught. See http://msdn.microsoft.com/en-us/library/system.stackoverflowexception(v=vs.110).aspx – Brian Rasmussen Sep 19 '14 at 02:46
  • @BrianRasmussen: A cast operation can't throw that anyway. (although a property setter could) – SLaks Sep 19 '14 at 02:52
  • 1
    @SLaks true, it was more a general comment about that particular exception. – Brian Rasmussen Sep 19 '14 at 04:05
  • Regarding your point about the `try`-`catch` making the intent less clear, you could just encapsulate the code in a descriptively-named method or use a comment, so I don't think that aspect is necessarily a problem, especially if `try`-`catch` is the only way to do something due to the API you're working with. – Sam Sep 19 '14 at 04:42