Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and Why I should Explicitly throw an Exception

Tags:

c#

exception

I'm just trying to make my understanding of Exception mechanism more clear.
If something goes wrong when an app is executed, the runtime automatically throws an appropriate exception. If it is so, then why I should sometimes make some check and explicitly throw a specific exception?
How to identify such cases (when an exception should be explicitly thrown in code)?

I don't put any example here on purpose, because I'd like to get a general understanding of the throwing exceptions approach.

like image 400
rem Avatar asked Jul 06 '11 19:07

rem


1 Answers

I think the general approach should be Fail Fast - you want to identify and handle invalid program conditions as soon as possible, this would mean not just when a particular input is needed within your program logic but as soon as you "receive" this input (which could be way earlier in time and/or lines of codes).

For i.e. public methods that means validating an input first, and if appropriate throw an exception if the input violates what your method expects.

like image 181
BrokenGlass Avatar answered Oct 13 '22 00:10

BrokenGlass