Deniz Demir
Deniz Demir

Reputation: 281

Throw exception without any real errors?

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;

}

Upvotes: 0

Views: 2579

Answers (3)

Marcos Pereira
Marcos Pereira

Reputation: 1176

You should design your code such that the unintended state is never reached.

If it is reached, you missed something, and throwing an exception is adequate.

In these cases you would also want to fix the code if you notice one of these exceptions being thrown. The only case when this is not possible is when the exception are thrown for conditions you can't control.

Personally, I like to use Trace.Assert() for all errors that are not supposed to happen (unlike Debug.Assert(), these are kept in non-debug-build code). I also appreciate the time saved by not writing error messages for these errors that only I am supposed to debug (and that can only be solved by modifying the code).

For errors caused by external factors, I find throwing exceptions remains adequate.

Upvotes: 0

ΩmegaMan
ΩmegaMan

Reputation: 31721

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.

Upvotes: 1

pablocom
pablocom

Reputation: 141

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.

https://youtu.be/2f2elFRmeLE

Upvotes: 0

Related Questions