MrDave1999 / SimpleResults

A simple library to implement the Result pattern for returning from services
https://mrdave1999.github.io/SimpleResults
MIT License
103 stars 2 forks source link

Why are exceptions used for unexpected errors or exceptional situations? #58

Closed MrDave1999 closed 7 months ago

MrDave1999 commented 7 months ago

Exceptions were designed to report unexpected errors immediately to developers (or programmers). In this context, an unexpected error is a situation that should never have occurred, i.e. it is not part of the normal execution of an application. When this type of situation occurs, the developer must fix it immediately, in some cases they are bugs that need to be corrected from the source code, in other cases they are errors that must be corrected from a configuration file (for example, specifying the connection string correctly).

For that reason, an exception object includes valuable information for the developer as support when correcting an unexpected error:

Knowing this, it can be deduced that the exceptions are closely related to the developer, it facilitates the programming too much and allows him to know immediately the cause of the unexpected error.

That is why it does not make sense to use exceptions for expected errors, which are part of the execution of the application, it is normal that they happen and that does not prevent the application to continue working without any problem. For example, let's imagine that a normal user does not enter the username and email address. These fields are required, should I throw an exception?

In that case it makes no sense to throw an exception, it is an error caused by the end user, it has nothing to do with the developer, therefore, the valuable information contained in an exception object, especially the stack trace, will remain unused if I decide to throw an exception for that situation. In fact, it is completely normal for that error to happen, it is something I would expect to happen.