I have read about why we need to throw an exception and Rethrow it. But I have confused about when Rethrow an exception? I added an example when I put throw in CalculationOperationNotSupportedException catch, and after that, I compared Stack Trace with Rethrowing and without Rethrowing. It's the same 99%, but when you rethrow an exception, it just adds location. Of course, if you accurately two stack trace. Line 35 is "throw" location number, and line 28 is int result = calculator.Calculate(number1, number2, operation); I think Stack Trace without rethrowing in here is better. What do you think about that?
Stack Trace without rethrowing(throw) I commented it.
at ConsoleCalculator.Calculator.Calculate(Int32 number1, Int32 number2, String operation) in C:\Users\Behnam\Desktop\c-sharp-error-handling-exceptions\06\demos\after\03UsingExceptions\ConsoleCalculator\Calculator.cs:line 25 at ConsoleCalculator.Program.Main(String[] args) in C:\Users\Behnam\Desktop\c-sharp-error-handling-exceptions\06\demos\after\03UsingExceptions\ConsoleCalculator\Program.cs:line 28
Stack Trace with rethrow in catch (CalculationOperationNotSupportedException ex)
at ConsoleCalculator.Calculator.Calculate(Int32 number1, Int32 number2, String operation) in C:\Users\Behnam\Desktop\c-sharp-error-handling-exceptions\06\demos\after\03UsingExceptions\ConsoleCalculator\Calculator.cs:line 25 at ConsoleCalculator.Program.Main(String[] args) in C:\Users\Behnam\Desktop\c-sharp-error-handling-exceptions\06\demos\after\03UsingExceptions\ConsoleCalculator\Program.cs:line 35
public int Calculate(int number1, int number2, string operation)
{
string nonNullOperation =
operation ?? throw new ArgumentNullException(nameof(operation));
if (nonNullOperation == "/")
{
try
{
return Divide(number1, number2);
}
catch (ArithmeticException ex)
{
throw new CalculationException("An error occurred during division", ex);
}
}
else
{
throw new CalculationOperationNotSupportedException(operation);
}
}
static void Main(string[] args)
{
var calculator = new Calculator();
int number1=1;
int number2=1;
string operation = "+";
try
{
int result = calculator.Calculate(number1, number2, operation);
DisplayResult(result);
}
catch (CalculationOperationNotSupportedException ex)
{
// Log.Error(ex);
WriteLine(ex);
throw;
}
}