<p>I have exceptions created for every condition that my application does not expect.  <code>UserNameNotValidException</code>, <code>PasswordNotCorrectException</code> etc.</p>

<p>However I was told I should not create exceptions for those conditions. In my UML those ARE exceptions to the main flow, so why should it not be an exception?</p>

<p>Any guidance or best practices for creating exceptions?</p>

[{'answer_id': 77161, 'author': 'Mitchel Sellers', 'author_id': 13279, 'author_profile': 'https://Stackoverflow.com/users/13279', 'pm_score': 4, 'selected': False, 'text': '<p>Exceptions are a somewhat costly effect, if for example you have a user that provides an invalid password, it is typically a better idea to pass back a failure flag, or some other indicator that it is invalid.</p>\n\n<p>This is due to the way that exceptions are handled, true bad input, and unique critical stop items should be exceptions, but not failed login info.</p>\n'}, {'answer_id': 77164, 'author': 'blowdart', 'author_id': 2525, 'author_profile': 'https://Stackoverflow.com/users/2525', 'pm_score': 8, 'selected': False, 'text': "<p>Because they're things that will happen normally. Exceptions are not control flow mechanisms. Users often get passwords wrong, it's not an exceptional case. Exceptions should be a truly rare thing, <code>UserHasDiedAtKeyboard</code> type situations.</p>\n"}, {'answer_id': 77175, 'author': 'EricSchaefer', 'author_id': 8976, 'author_profile': 'https://Stackoverflow.com/users/8976', 'pm_score': 5, 'selected': False, 'text': "<p>It is NOT an exception if the username is not valid or the password is not correct. Those are things you should expect in the normal flow of operation. Exceptions are things that are not part of the normal program operation and are rather rare.</p>\n<p>I do not like using exceptions because you can not tell if a method throws an exception just by looking at the call. Thats why exceptions should only be used if you can't handle the situation in a decent manner (think &quot;out of memory&quot; or &quot;computer is on fire&quot;).</p>\n"}, {'answer_id': 77179, 'author': 'Jon', 'author_id': 12261, 'author_profile': 'https://Stackoverflow.com/users/12261', 'pm_score': 4, 'selected': False, 'text': '<p>I think you should only throw an exception when there\'s nothing you can do to get out of your current state. For example if you are allocating memory and there isn\'t any to allocate. In the cases you mention you can clearly recover from those states and can return an error code back to your caller accordingly.</p>\n\n<hr>\n\n<p>You will see plenty of advice, including in answers to this question, that you should throw exceptions only in "exceptional" circumstances. That seems superficially reasonable, but is flawed advice, because it replaces one question ("when should I throw an exception") with another subjective question ("what is exceptional"). Instead, follow the advice of Herb Sutter (for C++, available in the <a href="http://www.drdobbs.com/when-and-how-to-use-exceptions/184401836" rel="noreferrer">Dr Dobbs article <em>When and How to Use Exceptions</em></a>, and also in his book with Andrei Alexandrescu, <em>C++ Coding Standards</em>): throw an exception if, and only if</p>\n\n<ul>\n<li>a precondition is not met (which typically makes one of the following\nimpossible) or</li>\n<li>the alternative would fail to meet a post-condition or</li>\n<li>the alternative would fail to maintain an invariant.</li>\n</ul>\n\n<p>Why is this better? Doesn\'t it replace the question with <em>several</em> questions about preconditions, postconditions and invariants? This is better for several connected reasons.</p>\n\n<ul>\n<li>Preconditions, postconditions and invariants are <em>design</em> characteristics of our program (its internal API), whereas the decision to <code>throw</code> is an implementation detail. It forces us to bear in mind that we must consider the design and its implementation separately, and our job while implementing a method is to produce something that satisfies the design constraints.</li>\n<li>It forces us to think in terms of preconditions, postconditions and invariants, which are the <em>only</em> assumptions that callers of our method should make, and are expressed precisely, enabling loose coupling between the components of our program.</li>\n<li>That loose coupling then allows us to refactor the implementation, if necessary.</li>\n<li>The post-conditions and invariants are testable; it results in code that can be easily unit tested, because the post-conditions are predicates our unit-test code can check (assert).</li>\n<li>Thinking in terms of post-conditions naturally produces a design that has <em>success as a post-condition</em>, which is the natural style for using exceptions. The normal ("happy") execution path of your program is laid out linearly, with all the error handling code moved to the <code>catch</code> clauses.</li>\n</ul>\n'}, {'answer_id': 77180, 'author': 'japollock', 'author_id': 1210318, 'author_profile': 'https://Stackoverflow.com/users/1210318', 'pm_score': 5, 'selected': False, 'text': "<p>One rule of thumb is to use exceptions in the case of something you couldn't normally predict.  Examples are database connectivity, missing file on disk, etc.  For scenarios that you can predict, ie users attempting to log in with a bad password you should be using functions that return booleans and know how to handle the situation gracefully.  You don't want to abruptly end execution by throwing an exception just because someone mistyped their password.</p>\n"}, {'answer_id': 77189, 'author': 'Shachar', 'author_id': 13897, 'author_profile': 'https://Stackoverflow.com/users/13897', 'pm_score': 3, 'selected': False, 'text': '<p>Exception classes are like "normal" classes. You create a new class when it "is" a different type of object, with different fields and different operations.</p>\n\n<p>As a rule of thumb, you should try balance between the number of exceptions and the granularity of the exceptions. If your method throws more than 4-5 different exceptions, you can probably merge some of them into more "general" exceptions, (e.g. in your case "AuthenticationFailedException"), and using the exception message to detail what went wrong. Unless your code handles each of them differently, you needn\'t creates many exception classes. And if it does, may you should just return an enum with the error that occured. It\'s a bit cleaner this way.</p>\n'}, {'answer_id': 77197, 'author': 'Sam', 'author_id': 9406, 'author_profile': 'https://Stackoverflow.com/users/9406', 'pm_score': 1, 'selected': False, 'text': '<p>the main reason for avoiding throwing an exception is that there is a lot of overhead involved with throwing an exception.</p>\n\n<p>One thing the article below states is that an exception is for an exceptional conditions and errors.</p>\n\n<p>A wrong user name is not necessarily a program error but a user error...</p>\n\n<p>Here is a decent starting point for exceptions within .NET:\n<a href="http://msdn.microsoft.com/en-us/library/ms229030(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms229030(VS.80).aspx</a></p>\n'}, {'answer_id': 77227, 'author': 'Gord', 'author_id': 12560, 'author_profile': 'https://Stackoverflow.com/users/12560', 'pm_score': 2, 'selected': False, 'text': '<p>In general you want to throw an exception for anything that can happen in your application that is "Exceptional"</p>\n\n<p>In your example, both of those exceptions look like you are calling them via a password / username validation.  In that case it can be argued that it isn\'t really exceptional that someone would mistype a username / password.</p>\n\n<p>They are "exceptions" to the main flow of your UML but are more "branches" in the processing.</p>\n\n<p>If you attempted to access your passwd file or database and couldn\'t, that would be an exceptional case and would warrant throwing an exception.</p>\n'}, {'answer_id': 77235, 'author': 'Jason Etheridge', 'author_id': 2193, 'author_profile': 'https://Stackoverflow.com/users/2193', 'pm_score': 2, 'selected': False, 'text': "<p>Firstly, if the users of your API aren't interested in specific, fine-grained failures, then having specific exceptions for them isn't of any value.</p>\n\n<p>Since it's often not possible to know what may be useful to your users, a better approach is to have the specific exceptions, but ensure they inherit from a common class (e.g., std::exception or its derivatives in C++). That allows your client to catch specific exceptions if they choose, or the more general exception if they don't care.</p>\n"}, {'answer_id': 77248, 'author': 'Charles Graham', 'author_id': 7705, 'author_profile': 'https://Stackoverflow.com/users/7705', 'pm_score': 3, 'selected': False, 'text': "<p>If it's code running inside a loop that will likely cause an exception over and over again, then throwing exceptions is not a good thing, because they are pretty slow for large N.  But there is nothing wrong with throwing custom exceptions if the performance is not an issue.  Just make sure that you have a base exception that they all inherite, called BaseException or something like that.  BaseException inherits System.Exception, but all of your exceptions inherit BaseException.  You can even have a tree of Exception types to group similar types, but this may or may not be overkill.</p>\n\n<p>So, the short answer is that if it doesn't cause a significant performance penalty (which it should not unless you are throwing a lot of exceptions), then go ahead.</p>\n"}, {'answer_id': 77250, 'author': 'Serhat Ozgel', 'author_id': 31505, 'author_profile': 'https://Stackoverflow.com/users/31505', 'pm_score': 0, 'selected': False, 'text': "<p>You may use a little bit generic exceptions for that conditions. For e.g. ArgumentException is meant to be used when anything goes wrong with the parameters to a method (with the exception of ArgumentNullException). Generally you would not need exceptions like LessThanZeroException, NotPrimeNumberException etc. Think of the user of your method. The number of the conditions that she will want to handle specifically is equal to the number of the type of the exceptions that your method needs to throw. This way, you can determine how detailed exceptions you will have.</p>\n\n<p>By the way, always try to provide some ways for users of your libraries to avoid exceptions. TryParse is a good example, it exists so that you don't have to use int.Parse and catch an exception. In your case, you may want to provide some methods to check if user name is valid or password is correct so your users (or you) will not have to do lots of exception handling. This will hopefully result in more readble code and better performance.</p>\n"}, {'answer_id': 77256, 'author': 'Arno', 'author_id': 13685, 'author_profile': 'https://Stackoverflow.com/users/13685', 'pm_score': 1, 'selected': False, 'text': "<p>Throwing exceptions causes the stack to unwind, which has some performance impacts (admitted, modern managed environments have improved on that). Still repeatedly throwing and catching exceptions in a nested situation would be a bad idea.</p>\n\n<p>Probably more important than that, exceptions are meant for exceptional conditions. They should not be used for ordinary control flow, because this will hurt your code's readability.</p>\n"}, {'answer_id': 77308, 'author': 'eli', 'author_id': 5105, 'author_profile': 'https://Stackoverflow.com/users/5105', 'pm_score': 0, 'selected': False, 'text': "<p>Ultimately the decision comes down to whether it is more helpful to deal with application-level errors like this using exception handling, or via your own home-rolled mechanism like returning status codes.  I don't think there's a hard-and-fast rule about which is better, but I would consider:</p>\n\n<ul>\n<li>Who's calling your code?  Is this a public API of some sort or an internal library?</li>\n<li>What language are you using?  If it's Java, for example, then throwing a (checked) exception puts an explicit burden on your caller to handle this error condition in some way, as opposed to a return status which could be ignored.  That could be good or bad.</li>\n<li>How are other error conditions in the same application handled?  Callers won't want to deal with a module that handles errors in an idiosyncratic way unlike anything else in the system.</li>\n<li>How many things can go wrong with the routine in question, and how would they be handled differently?  Consider the difference between a series of catch blocks that handle different errors and a switch on an error code.</li>\n<li>Do you have structured information about the error you need to return?  Throwing an exception gives you a better place to put this information than just returning a status.</li>\n</ul>\n"}, {'answer_id': 77361, 'author': 'The Digital Gabeg', 'author_id': 12782, 'author_profile': 'https://Stackoverflow.com/users/12782', 'pm_score': 10, 'selected': True, 'text': '<p>My personal guideline is: an exception is thrown when a fundamental assumption of the current code block is found to be false.</p>\n\n<p>Example 1: say I have a function which is supposed to examine an arbitrary class and return true if that class inherits from List&lt;>. This function asks the question, "Is this object a descendant of List?" This function should never throw an exception, because there are no gray areas in its operation - every single class either does or does not inherit from List&lt;>, so the answer is always "yes" or "no".</p>\n\n<p>Example 2: say I have another function which examines a List&lt;> and returns true if its length is more than 50, and false if the length is less. This function asks the question, "Does this list have more than 50 items?" But this question makes an assumption - it assumes that the object it is given is a list. If I hand it a NULL, then that assumption is false. In that case, if the function returns <i>either</i> true <i>or</i> false, then it is breaking its own rules. The function cannot return <i>anything</i> and claim that it answered the question correctly. So it doesn\'t return - it throws an exception.</p>\n\n<p>This is comparable to the <a href="http://en.wikipedia.org/wiki/Fallacy_of_many_questions" rel="noreferrer">"loaded question"</a> logical fallacy. Every function asks a question. If the input it is given makes that question a fallacy, then throw an exception. This line is harder to draw with functions that return void, but the bottom line is: if the function\'s assumptions about its inputs are violated, it should throw an exception instead of returning normally.</p>\n\n<p>The other side of this equation is: if you find your functions throwing exceptions frequently, then you probably need to refine their assumptions.</p>\n'}, {'answer_id': 77419, 'author': 'Bjorn Reppen', 'author_id': 1324220, 'author_profile': 'https://Stackoverflow.com/users/1324220', 'pm_score': 5, 'selected': False, 'text': "<p>Others propose that exceptions should not be used because the bad login is to be expected in a normal flow if the user mistypes.  I disagree and I don't get the reasoning.  Compare it with opening a file.. if the file doesn't exist or is not available for some reason then an exception will be thrown by the framework.  Using the logic above this was a mistake by Microsoft.  They should have returned an error code.  Same for parsing, webrequests, etc., etc.. </p>\n\n<p>I don't consider a bad login part of a normal flow, it's exceptional.   Normally the user types the correct password, and the file does exist.  The exceptional cases are exceptional and it's perfectly fine to use exceptions for those.  Complicating your code by propagating return values through n levels up the stack is a waste of energy and will result in messy code.  Do the simplest thing that could possibly work.  Don't prematurely optimize by using error codes, exceptional stuff by definition rarely happens, and exceptions don't cost anything unless you throw them.</p>\n"}, {'answer_id': 77595, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>I have three type of conditions that I catch.  </p>\n\n<ol>\n<li><p>Bad or missing input should not be an exception.  Use both client side js and server side regex to detect, set attributes and forward back to the same page with messages.</p></li>\n<li><p>The AppException.  This is usually an exception that you detect and throw with in your code.  In other words these are ones you expect (the file does not exist).  Log it, set the message, and forward back to the general error page.  This page usually has a bit of info about what happened.</p></li>\n<li><p>The unexpected Exception. These are the ones you don't know about. Log it with details and forward them to a general error page.</p></li>\n</ol>\n\n<p>Hope this helps</p>\n"}, {'answer_id': 77692, 'author': 'Joe Skora', 'author_id': 14057, 'author_profile': 'https://Stackoverflow.com/users/14057', 'pm_score': 2, 'selected': False, 'text': '<p>Exceptions are intended for events that are abnormal behaviors, errors, failures, and such.  Functional behavior, user error, etc., should be handled by program logic instead.  Since a bad account or password is an expected part of the logic flow in a login routine, it should be able to handle those situations without exceptions.</p>\n'}, {'answer_id': 78087, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': -1, 'selected': False, 'text': '<p>The exceptions versus returning error code argument should be about flow control not philosophy (how "exceptional" an error is):</p>\n\n<pre><code>void f1() throws ExceptionType1, ExceptionType2 {}\n\nvoid catchFunction() {\n  try{\n    while(someCondition){\n      try{\n        f1(); \n      }catch(ExceptionType2 e2){\n        //do something, don\'t break the loop\n      }\n    }\n  }catch(ExceptionType1 e1){\n    //break the loop, do something else\n  }\n</code></pre>\n\n<p>}</p>\n'}, {'answer_id': 78232, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Security is conflated with your example: You shouldn\'t tell an attacker that a username exists, but the password is wrong. That\'s extra information you don\'t need to share. Just say "the username or password is incorrect."</p>\n'}, {'answer_id': 78337, 'author': 'Robert', 'author_id': 14364, 'author_profile': 'https://Stackoverflow.com/users/14364', 'pm_score': 3, 'selected': False, 'text': '<p>I would say there are no hard and fast rules on when to use exceptions. However there  are good reasons for using or not using them:</p>\n\n<p>Reasons to use exceptions:</p>\n\n<ul>\n<li>The code flow for the common case is clearer</li>\n<li>Can return complex error information as an object (although this can also be achieved using error "out" parameter passed by reference)</li>\n<li>Languages generally provide some facility for managing tidy cleanup in the event of the exception (try/finally in Java, using in C#, RAII in C++)</li>\n<li>In the event no exception is thrown, execution can <em>sometimes</em> be faster than checking return codes</li>\n<li>In Java, checked exceptions must be declared or caught (although this can be a reason against)</li>\n</ul>\n\n<p>Reasons not to use exceptions:</p>\n\n<ul>\n<li>Sometimes it\'s overkill if the error handling is simple</li>\n<li>If exceptions are not documented or declared, they may be uncaught by calling code, which may be worse than if the the calling code just ignored a return code (application exit vs silent failure - which is worse may depend on the scenario)</li>\n<li>In C++, code that uses exceptions must be exception safe (even if you don\'t throw or catch them, but call a throwing function indirectly)</li>\n<li>In C++, it is hard to tell when a function might throw, therefore you must be paranoid about exception safety if you use them</li>\n<li>Throwing and catching exceptions is generally significantly more expensive compared to checking a return flag</li>\n</ul>\n\n<p>In general, I would be more inclined to use exceptions in Java than in C++ or C#, because I am of the opinion that an exception, declared or not, is fundamentally part of the formal interface of a function, since changing your exception guarantee may break calling code. The biggest advantage of using them in Java IMO, is that you know that your caller MUST handle the exception, and this improves the chance of correct behaviour.</p>\n\n<p>Because of this, in any language, I would always derive all exceptions in a layer of code or API from a common class, so that calling code can always guarantee to catch all exceptions. Also I would consider  it bad to throw exception classes that are implementation-specific, when writing an API or library (i.e.  wrap exceptions from lower layers so that the exception that your caller receives is understandable in the context of your interface).</p>\n\n<p>Note that Java makes the distinction between general and Runtime exceptions in that the latter need not be declared. I would only use Runtime exception classes when you know that the error is a result of a bug in the program.</p>\n'}, {'answer_id': 78500, 'author': 'dclaysmith', 'author_id': 14378, 'author_profile': 'https://Stackoverflow.com/users/14378', 'pm_score': 2, 'selected': False, 'text': '<p>I agree with japollock way up there--throw an acception when you are uncertain about the outcome of an operation. Calls to APIs, accessing filesystems, database calls, etc. Anytime you are moving past the "boundaries" of your programming languages.</p>\n\n<p>I\'d like to add, feel free to throw a standard exception. Unless you are going to do something "different" (ignore, email, log, show that twitter whale picture thingy, etc), then don\'t bother with custom exceptions.</p>\n'}, {'answer_id': 78935, 'author': 'Crusty', 'author_id': 9810, 'author_profile': 'https://Stackoverflow.com/users/9810', 'pm_score': -1, 'selected': False, 'text': '<p>There are two main classes of exception: </p>\n\n<p>1) System exception (eg Database connection lost) or \n2) User exception. (eg User input validation, \'password is incorrect\')</p>\n\n<p>I found it helpful to create my own User Exception Class and when I want to throw a user error I want to be handled differently (ie resourced error displayed to the user) then all I need do in my main error handler is check the object type:</p>\n\n<pre><code>            If TypeName(ex) = "UserException" Then\n               Display(ex.message)\n            Else\n               DisplayError("An unexpected error has occured, contact your help  desk")                   \n               LogError(ex)\n            End If\n</code></pre>\n'}, {'answer_id': 79187, 'author': 'Mike Kantor', 'author_id': 14607, 'author_profile': 'https://Stackoverflow.com/users/14607', 'pm_score': 0, 'selected': False, 'text': "<p>Some useful things to think about when deciding whether an exception is appropriate:</p>\n\n<ol>\n<li><p>what level of code you want to have run after the exception candidate occurs - that is, how many layers of the call stack should unwind. You generally want to handle an exception as close as possible to where it occurs. For username/password validation, you would normally handle failures in the same block of code, rather than letting an exception bubble up. So an exception is probably not appropriate. (OTOH, after three failed login attempts, control flow may shift elsewhere, and an exception may be appropriate here.)</p></li>\n<li><p>Is this event something you would want to see in an error log? Not every exception is written to an error log, but it's useful to ask whether this entry in an error log would be useful - i.e., you would try to do something about it, or would be the garbage you ignore.</p></li>\n</ol>\n"}, {'answer_id': 79931, 'author': 'core', 'author_id': 11574, 'author_profile': 'https://Stackoverflow.com/users/11574', 'pm_score': 2, 'selected': False, 'text': '<p>The simple answer is, whenever an operation is impossible (because of either application OR because it would violate business logic). If a method is invoked and it impossible to do what the method was written to do, throw an Exception. A good example is that constructors always throw ArgumentExceptions if an instance cannot be created using the supplied parameters. Another example is InvalidOperationException, which is thrown when an operation cannot be performed because of the state of another member or members of the class.</p>\n\n<p>In your case, if a method like Login(username, password) is invoked, if the username is not valid, it is indeed correct to throw a UserNameNotValidException, or PasswordNotCorrectException if password is incorrect. The user cannot be logged in using the supplied parameter(s) (i.e. it\'s impossible because it would violate authentication), so throw an Exception. Although I might have your two Exceptions inherit from ArgumentException.</p>\n\n<p>Having said that, if you wish NOT to throw an Exception because a login failure may be very common, one strategy is to instead create a method that returns types that represent different failures. Here\'s an example:</p>\n\n<pre><code>{ // class\n    ...\n\n    public LoginResult Login(string user, string password)\n    {\n        if (IsInvalidUser(user))\n        {\n            return new UserInvalidLoginResult(user);\n        }\n        else if (IsInvalidPassword(user, password))\n        {\n            return new PasswordInvalidLoginResult(user, password);\n        }\n        else\n        {\n            return new SuccessfulLoginResult();\n        }\n    }\n\n    ...\n}\n\npublic abstract class LoginResult\n{\n    public readonly string Message;\n\n    protected LoginResult(string message)\n    {\n        this.Message = message;\n    }\n}\n\npublic class SuccessfulLoginResult : LoginResult\n{\n    public SucccessfulLogin(string user)\n        : base(string.Format("Login for user \'{0}\' was successful.", user))\n    { }\n}\n\npublic class UserInvalidLoginResult : LoginResult\n{\n    public UserInvalidLoginResult(string user)\n        : base(string.Format("The username \'{0}\' is invalid.", user))\n    { }\n}\n\npublic class PasswordInvalidLoginResult : LoginResult\n{\n    public PasswordInvalidLoginResult(string password, string user)\n        : base(string.Format("The password \'{0}\' for username \'{0}\' is invalid.", password, user))\n    { }\n}\n</code></pre>\n\n<p>Most developers are taught to avoid Exceptions because of the overhead caused by throwing them. It\'s great to be resource-conscious, but usually not at the expense of your application design. That is probably the reason you were told not to throw your two Exceptions. Whether to use Exceptions or not usually boils down to how frequently the Exception will occur. If it\'s a fairly common or an fairly expectable result, this is when most developers will avoid Exceptions and instead create another method to indicate failure, because of the supposed consumption of resources.</p>\n\n<p>Here\'s an example of avoiding using Exceptions in a scenario like just described, using the Try() pattern:</p>\n\n<pre><code>public class ValidatedLogin\n{\n    public readonly string User;\n    public readonly string Password;\n\n    public ValidatedLogin(string user, string password)\n    {\n        if (IsInvalidUser(user))\n        {\n            throw new UserInvalidException(user);\n        }\n        else if (IsInvalidPassword(user, password))\n        {\n            throw new PasswordInvalidException(password);\n        }\n\n        this.User = user;\n        this.Password = password;\n    }\n\n    public static bool TryCreate(string user, string password, out ValidatedLogin validatedLogin)\n    {\n        if (IsInvalidUser(user) || \n            IsInvalidPassword(user, password))\n        {\n            return false;\n        }\n\n        validatedLogin = new ValidatedLogin(user, password);\n\n        return true;\n    }\n}\n</code></pre>\n'}, {'answer_id': 80458, 'author': 'Petr Macek', 'author_id': 15045, 'author_profile': 'https://Stackoverflow.com/users/15045', 'pm_score': 2, 'selected': False, 'text': "<p>I'd say that generally every fundamentalism leads to hell. </p>\n\n<p>You certainly wouldn't want to end up with exception driven flow, but avoiding exceptions altogether is also a bad idea. You have to find a balance between both approaches. What I would not do is to create an exception type for every exceptional situation. That is not productive.</p>\n\n<p>What I generally prefer is to create two basic types of exceptions which are used throughout the system: <em>LogicalException</em> and <em>TechnicalException</em>. These can be further distinguished by subtypes if needed, but it is not generally not necessary. </p>\n\n<p>The technical exception denotes the really unexpected exception like database server being down, the connection to the web service threw the IOException and so on. </p>\n\n<p>On the other hand the logical exceptions are used to propagate the less severe erroneous situation to the upper layers (generally some validation result). </p>\n\n<p>Please note that even the logical exception is not intended to be used on regular basis to control the program flow, but rather to highlight the situation when the flow should really end. When used in Java, both exception types are <em>RuntimeException</em> subclasses and error handling is highly aspect oriented. </p>\n\n<p>So in the login example it might be wise to create something like AuthenticationException and distinguish the concrete situations by enum values like <em>UsernameNotExisting</em>, <em>PasswordMismatch</em> etc. Then you won't end up in having a huge exception hierarchy and can keep the catch blocks on maintainable level. You can also easily employ some generic exception handling mechanism since you have the exceptions categorized and know pretty well what to propagate up to the user and how.</p>\n\n<p>Our typical usage is to throw the LogicalException during the Web Service call when the user's input was invalid. The Exception gets marshalled to the SOAPFault detail and then gets unmarshalled to the exception again on the client which is resulting in showing the validation error on one certain web page input field since the exception has proper mapping to that field.</p>\n\n<p>This is certainly not the only situation: you don't need to hit web service to throw up the exception. You are free to do so in any exceptional situation (like in the case you need to fail-fast) - it is all at your discretion.</p>\n"}, {'answer_id': 81151, 'author': 'Commander Keen', 'author_id': 13194, 'author_profile': 'https://Stackoverflow.com/users/13194', 'pm_score': 6, 'selected': False, 'text': '<p>My little guidelines are heavily influenced by the great book "Code complete":</p>\n\n<ul>\n<li>Use exceptions to notify about things that should not be ignored. </li>\n<li>Don\'t use exceptions if the error can be handled locally</li>\n<li>Make sure the exceptions are at the same level of abstraction as the rest of your routine.</li>\n<li>Exceptions should be reserved for what\'s <strong>truly exceptional</strong>. </li>\n</ul>\n'}, {'answer_id': 86263, 'author': 'Dan', 'author_id': 8040, 'author_profile': 'https://Stackoverflow.com/users/8040', 'pm_score': 1, 'selected': False, 'text': '<p>I have philosophical problems with the use of exceptions. Basically, you are expecting a specific scenario to occur, but rather than handling it explicitly you are pushing the problem off to be handled "elsewhere." And where that "elsewhere" is can be anyone\'s guess.</p>\n'}, {'answer_id': 3112033, 'author': 'supercat', 'author_id': 363751, 'author_profile': 'https://Stackoverflow.com/users/363751', 'pm_score': 1, 'selected': False, 'text': '<p>To my mind, the fundamental question should be whether one would expect that the caller would want to continue normal program flow if a condition occurs.  If you don\'t know, either have separate doSomething and trySomething methods, where the former returns an error and the latter does not, or have a routine that accepts a parameter to indicate whether an exception should be thrown if it fails).  Consider a class to send commands to a remote system and report responses.  Certain commands (e.g. restart) will cause the remote system to send a response but then be non-responsive for a certain length of time.  It is thus useful to be able to send a "ping" command and find out whether the remote system responds in a reasonable length of time without having to throw an exception if it doesn\'t (the caller would probably expect that the first few "ping" attempts would fail, but one would eventually work).  On the other hand, if one has a sequence of commands like:</p>\n\n<pre>\n  exchange_command("open tempfile");\n  exchange_command("write tempfile data {whatever}");\n  exchange_command("write tempfile data {whatever}");\n  exchange_command("write tempfile data {whatever}");\n  exchange_command("write tempfile data {whatever}");\n  exchange_command("close tempfile");\n  exchange_command("copy tempfile to realfile");\n</pre>\n\n<p>one would want failure of any operation to abort the whole sequence.  While one could check each operation to ensure it succeeded, it\'s more helpful to have the exchange_command() routine throw an exception if a command fails.</p>\n\n<p>Actually, in the above scenario it may be helpful to have a parameter to select a number of failure-handling modes: never throw exceptions, throw exceptions for communication errors only, or throw exceptions in any cases where a command does not return a "success" indication.</p>\n'}, {'answer_id': 5392233, 'author': 'DanMan', 'author_id': 428241, 'author_profile': 'https://Stackoverflow.com/users/428241', 'pm_score': 0, 'selected': False, 'text': '<p>"PasswordNotCorrectException" isn\'t a good example for using exceptions. Users getting their passwords wrong is to be expected, so it\'s hardly an exception IMHO. You probably even recover from it, showing a nice error message, so it\'s just a validity check.</p>\n\n<p>Unhandled exceptions will stop the execution eventually - which is good. If you\'re returning false, null or error codes, you will have to deal with the program\'s state all by yourself. If you forget to check conditions somewhere, your program may keep running with wrong data, and you may have a hard time figuring out <em>what</em> happened and <em>where</em>.</p>\n\n<p>Of course, you could cause the same problem with empty catch statements, but at least spotting those is easier and doesn\'t require you to understand the logic.</p>\n\n<p>So as a rule of thumb:</p>\n\n<p>Use them wherever you don\'t want or simply can\'t recover from an error.</p>\n'}, {'answer_id': 7676705, 'author': 'Genjuro', 'author_id': 978769, 'author_profile': 'https://Stackoverflow.com/users/978769', 'pm_score': 2, 'selected': False, 'text': '<p>for me Exception should be thrown when a required technical or business  rule  fails.\nfor instance if  a car entity is associated with array of 4 tires ... if  one tire or more are null ... an exception should be Fired "NotEnoughTiresException" , cuz it can be caught at different level of the system and have a significant meaning through logging.\nbesides if we just try to flow control the null and prevent the instanciation of the car .\nwe might never never find the source of the problem , cuz the tire isn\'t supposed to be null in the first place . </p>\n'}, {'answer_id': 8560585, 'author': 'goran', 'author_id': 1105768, 'author_profile': 'https://Stackoverflow.com/users/1105768', 'pm_score': 2, 'selected': False, 'text': '<p>the rule of thumb for throwing exceptions is pretty simple. you do so when your code has entered into an UNRECOVERABLE INVALID state. if data is compromised or you cannot wind back the processing that occurred up to the point then you must terminate it. indeed what else can you do? your processing logic will eventually fail elsewhere. if you can recover somehow then do that and do not throw exception.</p>\n\n<p>in your particular case if you were forced to do something silly like accept money withdrawal and only then check user/pasword you should terminate the process by throwing an exception to notify that something bad has happened and prevent further damage.</p>\n'}, {'answer_id': 23236815, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': -1, 'selected': False, 'text': '<p>Here are my suggestions:</p>\n\n<p>I don\'t think it\'s ALWAYS a good way to throw an exception because it will take more time, memory to process with such exceptions. </p>\n\n<p>In my mind, <strong>if something can be processed with a "kind,polite" way (this means if we can "predicate such errors by using if…… or something like this), we should AVOID using "exceptions" but just return a flag like "false" , with an outer parameter value telling him/her the detailled reason.</strong></p>\n\n<p>An example is, we can make a class like this following:</p>\n\n<pre><code>public class ValueReturnWithInfo&lt;T&gt;\n{\n   public T Value{get;private set;}\n   public string errorMsg{get;private set;}\n   public ValueReturnWithInfo(T value,string errmsg)\n   {\n      Value = value;\n      errMsg = errmsg;\n   }\n}\n</code></pre>\n\n<p>We can use such "multiple-value-returned" classes instead of errors, which seems to be a better,polite way to process with exception problems.</p>\n\n<p>However, notice that <strong>if some errors cannot be described so easily (this depends on your programming experience) with "if"……(such as FileIO exceptions), you have to throw exceptions</strong>.</p>\n'}, {'answer_id': 74203785, 'author': 'garcipat', 'author_id': 2372525, 'author_profile': 'https://Stackoverflow.com/users/2372525', 'pm_score': 0, 'selected': False, 'text': '<p>I would say that exceptions should be thrown if an unexpected behaviour is occuring that wasnt meant to be.</p>\n<p>Like trying to update or delete a non existing entity. And it should be catched where the Exception can be handled and has meaning. For working in an alternative way to continue, add logging or returning a specific result on Api level.</p>\n<p>If you expect something to be the case, you should build code to check and ensure it.</p>\n'}]
['https://Stackoverflow.com/questions/77127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/279750/']