Can I use try-catch-throw for conditions that I set up, instead of actual errors? For example,
int x = 0;
if (x > 0)
{ throw new Exception("X can't be more than 0!");}
So there is nothing technically wrong with x being more than 0 but it is the condition that I have. Also, I know throw terminates the program but I need the program to keep running afterwards.
EDIT: Here is part of my code that I'm trying to implement this on:
public bool CheckIfEligible()
{
if (DateTime.Compare(DateTime.Now, this.startTime) > 0)
{
Console.WriteLine("\n" "ERROR: choose a later date");
return false;
}
// bunch of other conditions here...
else
return true;
}
CodePudding user response:
Actually is generally a good practice to create custom exceptions that represents exceptional cases for your domain.
public class StartCannotBeInThePastException : Exception
{
public StartCannotBeInThePastException(string message) : base(message)
{ }
}
That way to can handle specifically those exceptions that represents specific domain related errors, then log details or returning back to clients instead of making application crash for example. Also another benefit of doing custom exceptions is that you make your bussines rules explicit in the code, making it easier to read.
In this example would be something like this:
public void CheckIfEligible()
{
if (DateTime.Now > this.startTime)
{
throw new StartCannotBeInThePastException();
}
}
Exceptions have some hidden performance cost, if you are interested in that I leave you this video which explains it nice.
CodePudding user response:
This assumes you are not providing this code as a library somewhere, but are mainly concerned about doing these type of checks while you are developing it.
C# has the [ConditionalAttribute("DEBUG")]
attribute which one can be add to a method which will do those checks, only when the code is in DEBUG
mode and not release.
Why?
It allows to do sanity checks before we release.
What it means is, that the call and the method used, should only be compiled if this is a debug mode build. When the code is being built in Release
mode, it won't ever be called or compiled into the exe; hence not doing development checks in release code that most likely won't see a development type failure.
For example
[ConditionalAttribute("DEBUG")]
private void CheckIfEligible(DateTime start, Datetime end)
{
if (DateTime.Compare(DateTime.Now, startTime) > 0)
Console.WriteLine($"{Environment.Newline}ERROR: choose a later date");
if (start > end)
Console.WriteLine($"{Environment.Newline}ERROR: choose a earlier date");
}
Then in your code do something like this.
public void MyOperation()
{
....
CheckIfEligible(myStartTime, myEndTime);
// Normal processing no extra checks needed
If () ...
}
This allows you to do the sanity checks which this process seems to suggest you want without compromising the end result.