βœ… Different output on same code.

return arithmetic.Calculate(Convert.ToDecimal(left, CultureInfo.InvariantCulture), token, Convert.ToDecimal(right, CultureInfo.InvariantCulture));
return arithmetic.Calculate(Convert.ToDecimal(left, CultureInfo.InvariantCulture), token, Convert.ToDecimal(right, CultureInfo.InvariantCulture));
No description
No description
36 Replies
Merineth πŸ‡ΈπŸ‡ͺ
Is there a reason for this?
Pobiega
Pobiegaβ€’3w ago
yes or rather, there could be. Break that line up into smaller segments so its more easily debuggable , vs . is a common source of errors when it comes to converting, so double check that 3.8 isnt being read as 38 since your output is 787,5 on the left, and 78.75 on the right (note that one has comma, the other does not)
Merineth πŸ‡ΈπŸ‡ͺ
It's being read corrently
Merineth πŸ‡ΈπŸ‡ͺ
I'll have him fix it since it's his code :P I do have another question about exceptions, wondering if you could help Can exceptions accept parameters? For example...
public decimal Run(decimal number1, decimal number2)
{
try
{
return number1 / number2;
}
catch (DivideByZeroException)
{
throw new UDDivideByZeroException(number1, number2);
return 0;
}


}
public decimal Run(decimal number1, decimal number2)
{
try
{
return number1 / number2;
}
catch (DivideByZeroException)
{
throw new UDDivideByZeroException(number1, number2);
return 0;
}


}
UDDivideByZeroException is my own user defined exception
internal class UDDivideByZeroException : Exception
{
public UDDivideByZeroException(decimal number1, decimal number2)
{
Console.WriteLine($"Exception: Divide by zero: {number1}/{number2}");
}
}
internal class UDDivideByZeroException : Exception
{
public UDDivideByZeroException(decimal number1, decimal number2)
{
Console.WriteLine($"Exception: Divide by zero: {number1}/{number2}");
}
}
When it has thrown the exception, i want it to return 0; How is that done? Because currently as soon as it gets to throw new UDDivideByZeroException(number1, number2); the program stops Nvm i managed to solve it myself :p
public decimal Run(decimal number1, decimal number2)
{
try
{
return number1 / number2;
}
catch (DivideByZeroException)
{
var exception = new UDDivideByZeroException(number1, number2);
return 0;
}


}
public decimal Run(decimal number1, decimal number2)
{
try
{
return number1 / number2;
}
catch (DivideByZeroException)
{
var exception = new UDDivideByZeroException(number1, number2);
return 0;
}


}
Not entirely sure why that worked, but it worked.. :catHeyHello: I assume the difference is because we store the exception under exception instead of executing it?
Bailey
Baileyβ€’3w ago
catch (Exception ex) // this catches the exception and adds the exception is in the var ex. { var exception = new UDDivideByZeroException(number1, number2); // this just creates a local variable with a self defined exception return 0; // returns a 0 } } so it would work without: var exception = new UDDivideByZeroException(number1, number2);
Pobiega
Pobiegaβ€’3w ago
those are strings, not doubles/decimals/floats cmon we've been over this exceptions dont handle errors, they ARE errors so you throwing/creating your own exception after jsut catching another one is... pointless instead, just place that Console.WriteLine in your catch clause
Merineth πŸ‡ΈπŸ‡ͺ
I see So are user defined exceptions caught by using an if/else ? Or would it work with a try there also
Pobiega
Pobiegaβ€’3w ago
you're still not getting it user defined exceptions are the same as non-user defined ones they get thrown, you catch them in your case, you are catching division by zero. Thats not a user defined exception but CATCH is what handles exceptions, not Exception or new UserDefinedWhatever();
Merineth πŸ‡ΈπŸ‡ͺ
Ok so user defined exceptions are exceptions that define what is not allowed in our code?
Pobiega
Pobiegaβ€’3w ago
wellll not really they represent an instance of an error happening
Merineth πŸ‡ΈπŸ‡ͺ
Ok so user defined exceptions are exceptions that define AN INSTANCE of what is not allowed in our code?
Pobiega
Pobiegaβ€’3w ago
sorta here is an example
var user = new User { Role = Role.Normal };

Methods.DoAdminThing(user);

public class Methods
{
public static void DoAdminThing(User user)
{
if (user.Role == Role.Normal)
{
throw new UserPermissionException(Role.Admin, user.Role);
}
}
}

public class UserPermissionException : Exception
{
public Role Expected { get; }
public Role Actual { get; }

public UserPermissionException(Role expected, Role actual) : base($"Minimum role was {expected}, actual was {actual}")
{
Expected = expected;
Actual = actual;
}
}

public class User
{
public Role Role { get; set; }
}

public enum Role
{
Normal,
Admin,
}
var user = new User { Role = Role.Normal };

Methods.DoAdminThing(user);

public class Methods
{
public static void DoAdminThing(User user)
{
if (user.Role == Role.Normal)
{
throw new UserPermissionException(Role.Admin, user.Role);
}
}
}

public class UserPermissionException : Exception
{
public Role Expected { get; }
public Role Actual { get; }

public UserPermissionException(Role expected, Role actual) : base($"Minimum role was {expected}, actual was {actual}")
{
Expected = expected;
Actual = actual;
}
}

public class User
{
public Role Role { get; set; }
}

public enum Role
{
Normal,
Admin,
}
so we make a user, then we try to call a method that needs us to be admins for it to work because we are not admins, the code throws an error
Merineth πŸ‡ΈπŸ‡ͺ
:catsweat: Yeah i kindof understand what's happening
Pobiega
Pobiegaβ€’3w ago
btw, you can manually throw standard exceptions like, if you want to throw a DivisionByNullException, you can you dont need to make a custom one the purpose of custom ones are to represent other errors or expose data field that dont exist on normal ones like UserTriedToDoWeirdThingException(...) tells me more about the problem than InvalidOperationException()
Merineth πŸ‡ΈπŸ‡ͺ
That makes sense I kind of understand exceptions now however not sure how i'm meant to implement it
Pobiega
Pobiegaβ€’3w ago
what are you trying to do?
Merineth πŸ‡ΈπŸ‡ͺ
Oufh it's a little hard to explain but i'll do my best. So we are meant to create an RPN calculator. Where the input from the user such as 3 4 + returns 7 or it reads the input from a textfile input.txt and outputs it into output.txt. Essentially they want us to handle problems such as what if the user inputs 4 0 / where it tries to divide by zero. If the cass is that the user input the 4 0 / it should print to the console. But when the input.txt file is used it should print it to the textfile. I think i have an idea on what to do now when i am typing the explanation
try
{
decimal output = calculationHandler.Run(top);
Console.WriteLine("= {0}", output);
}
catch (DivideByZeroException)
{
Console.WriteLine("Exception: Divide by zero: ");
}
try
{
decimal output = calculationHandler.Run(top);
Console.WriteLine("= {0}", output);
}
catch (DivideByZeroException)
{
Console.WriteLine("Exception: Divide by zero: ");
}
The only problem i'm having is that after the Console.WriteLine("Exception: Divide by zero: "); it should look more like Console.WriteLine($"Exception: Divide by zero: {number1}/{number2}"); However number1 and number 2 aren't defined
Merineth πŸ‡ΈπŸ‡ͺ
If that makes sense? I do have a question tho
while (true){
try
{
decimal output = calculationHandler.Run(top);
if (output == 0)
{

}
Console.WriteLine("= {0}", output);
}
catch (DivideByZeroException)
{
Console.WriteLine($"Exception: Divide by zero: 4,00/0,00");
}
}
while (true){
try
{
decimal output = calculationHandler.Run(top);
if (output == 0)
{

}
Console.WriteLine("= {0}", output);
}
catch (DivideByZeroException)
{
Console.WriteLine($"Exception: Divide by zero: 4,00/0,00");
}
}
Inside the if, is there a function or keyword that restarts the loop from the top?
Jimmacle
Jimmacleβ€’3w ago
continue; will skip to the next loop iteration
Merineth πŸ‡ΈπŸ‡ͺ
fantastic I encountered a problem
try
{
decimal output = calculationHandler.Run(top);
if (output == 0)
{
continue;
}
Console.WriteLine("= {0}", output);
}
catch (DivideByZeroException)
{
Console.WriteLine($"Exception: Divide by zero: 4,00/0,00");
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("Invalid Operation");
}
try
{
decimal output = calculationHandler.Run(top);
if (output == 0)
{
continue;
}
Console.WriteLine("= {0}", output);
}
catch (DivideByZeroException)
{
Console.WriteLine($"Exception: Divide by zero: 4,00/0,00");
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("Invalid Operation");
}
The IndexOutOfRangeException applies to both the input 4 / 3 and A + B But they should be handled differently Exception: Invalid Operation Exception: Invalid token: A This should be the expected output of them Any ideas how i might resolve this?
Jimmacle
Jimmacleβ€’3w ago
what is calculationHandler?
Pobiega
Pobiegaβ€’3w ago
Ah, I see so, you could throw a custom exception here where you would put the numbers of the division your outer try could then get the numbers
Merineth πŸ‡ΈπŸ‡ͺ
Hmm
public class CalculationHandler
{

private Mystack stack;

// Constructor to initialize Calculation Handler
public CalculationHandler(Mystack stack)
{
this.stack = stack;
}

//Helper function to check if a token is a operator or not
static bool IsOperator(string token)
{
return token == "+" || token == "-" || token == "*" || token == "/" || token == "%";
}

public decimal Run(string token)
{
string right;
string left;
right = stack.pop();
if (IsOperator(right) == true)
{
right = Run(right).ToString();
}
left = stack.pop();
if (IsOperator(left) == true)
{
left = Run(left).ToString();
}
ArithmeticMethods arithmetic = new ArithmeticMethods();
return arithmetic.Calculate(Convert.ToDecimal(left, CultureInfo.InvariantCulture), token, Convert.ToDecimal(right, CultureInfo.InvariantCulture));


}
}
}
public class CalculationHandler
{

private Mystack stack;

// Constructor to initialize Calculation Handler
public CalculationHandler(Mystack stack)
{
this.stack = stack;
}

//Helper function to check if a token is a operator or not
static bool IsOperator(string token)
{
return token == "+" || token == "-" || token == "*" || token == "/" || token == "%";
}

public decimal Run(string token)
{
string right;
string left;
right = stack.pop();
if (IsOperator(right) == true)
{
right = Run(right).ToString();
}
left = stack.pop();
if (IsOperator(left) == true)
{
left = Run(left).ToString();
}
ArithmeticMethods arithmetic = new ArithmeticMethods();
return arithmetic.Calculate(Convert.ToDecimal(left, CultureInfo.InvariantCulture), token, Convert.ToDecimal(right, CultureInfo.InvariantCulture));


}
}
}
Pobiega
Pobiegaβ€’3w ago
ArithmeticMethods.Calculate is where you would catch the exception and re-throw it as your new type or detect the divide by zero at that point also, seems a bit weird that ArithmeticMethods.Calculate isnt static, but uses no state
Merineth πŸ‡ΈπŸ‡ͺ
Honestly i have no idea either, i didn't write CalculationHandler but i was assigned to handle the exceptions It gets really complicated
Pobiega
Pobiegaβ€’3w ago
Thats fine you'll need to go inside Calculate thou
Merineth πŸ‡ΈπŸ‡ͺ
Hmm okay i think i need to do it one thing at a time
Merineth πŸ‡ΈπŸ‡ͺ
Ok si i removed the try/catch and reran it with the input 4 0 / which resulted in me getting (obviously)
No description
Merineth πŸ‡ΈπŸ‡ͺ
So i would assume that the try/catch gets placed here.
Merineth πŸ‡ΈπŸ‡ͺ
The only problem here is that it's possible that i want it to do two different things and it's always expecting a return value which makes it problematic So essentially i can't use the try/catch inside the Division class. But if i go to the original class that called it
try
{
decimal output = calculationHandler.Run(top);
if (output == 0)
{
continue;
}
Console.WriteLine("= {0}", output);
}
catch (DivideByZeroException)
{
Console.WriteLine("Exception: Divide by zero: ");
}
try
{
decimal output = calculationHandler.Run(top);
if (output == 0)
{
continue;
}
Console.WriteLine("= {0}", output);
}
catch (DivideByZeroException)
{
Console.WriteLine("Exception: Divide by zero: ");
}
I can't specify which numbers are used. Since they aren't defined there
Pobiega
Pobiegaβ€’3w ago
okay so lets fix Run on division we dont need to catch anything, we can detect the division with a simple if and instead of running the division if its 0, just throw your own exception throw new MerinethDivisionByZero(number1, number2); then out in code that runs calculationHandler.Run we can catch that custom exception
Merineth πŸ‡ΈπŸ‡ͺ
namespace Calculator.Controller
{
public class AlexDivideByZeroException : Exception
{

}
}

namespace Calculator.Model
{
internal class Division
{
public decimal Run(decimal number1, decimal number2)
{
if (number2 == 0)
{
throw new AlexDivideByZeroException();
}
return number1 / number2;


}

}
}
namespace Calculator.Controller
{
public class AlexDivideByZeroException : Exception
{

}
}

namespace Calculator.Model
{
internal class Division
{
public decimal Run(decimal number1, decimal number2)
{
if (number2 == 0)
{
throw new AlexDivideByZeroException();
}
return number1 / number2;


}

}
}
And now i have to specify what i want it to do? Exceptions wants me to kms
Want results from more Discord servers?
Add your server