Is there a rule of thumb for handling exceptions wrt whether they should be handled in the same method of the exception-raising code or the caller?
In relation to this, what is the rule of thumb/general practise for deciding when to use “throw new” or catch blocks?
Thanks
Catch means you can handle the exception.
You should catch exceptions when you can handle the condition and do something useful. Otherwise you should let it bubble up the call stack and perhaps someone above you can handle it. Some apps have unhandled exception handlers to handle it at the outer most layer but in general, unless you know you have some useful way to handle it, let it go.
throw new means you’re creating an error condition that someone above you may want to catch. Remember that the callers may want to handle/catch your error so do not throw new “Exception” or “ApplicationException” – throw a specific exception type that inherits from exception so the user knows what they’re handling.
Last but not least, ensure exceptions are exceptional. Do not throw unless it’s an exceptional error case. For example, code that checks if something exists should not throw and catch – it causes the debugger to break and it’s expensive if called frequently. On our team, we always look for code to run clean if no error case was encountered.
Here’s a related post:
Trying to understand exceptions in C#