How to properly put statements inside a try-catch block? - c#

I need to execute a lot of statements, one after the other, and I need that when a sigle statement throws an exception the flow of the program continues executing the next statement, for example:
double a = Double.Parse("2.5");
double b = Double.Parse("ADFBBG");
Geometry g = Geometry.Parse("M150,0L75,200 225,200z");
All statements have to be executed, so I need a sort of try-catch blocks in cascade:
double a, b;
Geometry g;
try
{
a = Double.Parse("2.5");
}
catch
{}
try
{
b = Double.Parse("ADFBBG");
}
catch
{}
try
{
g = Geometry.Parse("M150,0L75,200 225,200z");
}
catch
{}
Obviously this is not the most elegant way to write my program. Is there a better way (more elegant, that does not reduce significantly the performance)?
I tried using the Func<TResult> delegate in such a way:
I wrote the following method:
T Try<T>(Func<T> func)
{
try
{
return func();
}
catch
{
return default(T);
}
}
So I can use it like this:
double x = Try(() => Double.Parse("77"));
Geometry g = Try(() => Geometry.Parse("M150,0L75,200 225,200z"));
Other solutions?

Use Double.TryParse.
It returns a value indicating whether the conversion was successfull. So you can use it the following way:
double converted;
bool success = Double.TryParse(value, out converted);
if (success)
{
// Do whatever you want
// The converted value is in the variable 'covnerted'
}

It seems that you don't care about which parse failed but just need a default value is case of failure? If so init your vars first to defaults then parse in a single try-catch:
double a=0.0, b=0.0;
Geometry g = new Geometry();
try
{
a = Double.Parse("2.5");
b = Double.Parse("ADFBBG");
g = Geometry.Parse("M150,0L75,200 225,200z");
}
catch
{
//At least mark that conversion was not succesful
}
Try-catch will only give you a performance hit when an exception is thrown. If all is well the impact of try-catch is minimal. see this question
A bit more elegant then your posted code but at least more concise.
Alternative with using TryParse
double a=0.0, b=0.0;
Geometry g = new Geometry();
Double.TryParse("2.5", out a);
Double.TryParse("ADFBBG", out b);
Geometry.TryParse("M150,0L75,200 225,200z", out g);
But there is a caveat: Geometry doesn't has TryParse implemented... (assuming that you use System.Windows.Media.Geometry)
That brings me to the point:
use your Try<> func, doens't reduce overhead but is clean
validate the string first. Removes the overhead of try but introduces runtime overhead on parsing.
Either way: validating userinput has it costs.
In answer to the main question: How to properly put statements inside a try-catch block?
If you don't care about which statement fails: 1 try-catch.
However: If the first statement fails, the other statement won't get executed. But, your system is already in in failed/corrupted state. Would further processing result in a correct result? (doubt it)

TryParse is more preferable, because you've no performance penalty on throwing and catching exception.
And one more inaccuracy in the above code - no difference between parsed "0" and default(T).
Code's more fast than yours
public static class StringExt
{
public static double ParseDouble(this string value)
{
double result;
Double.TryParse(value, out result);
return result;
}
}

I have answered a similar question a few days ago. If you have a collection of string values, you can use the power of extension methods to do just that.
static public IEnumerable<double> ConvertToDouble(this IEnumerable<string> source)
{
double x = 0;
var result = source.Where(str => Double.TryParse(str, out x))
.Select (str => x);
return result;
}
So put everything in a collection and use .AsEnumerable() followed by ConvertToDouble() extension method. Everything which cannot be parsed, will be ignored without an exception and the result is of type IEnumerable<Double>
Original answer: Convert List<string> to List<int> in C#
/edit: does the downvoter care to explain? The OP has not clarified, why he wants to use try catch and has not explained what has to be done in case of an exception. Hance I assume he does not want to do anything in case an exception is raised.

Related

Why is TryParse the way round that it is?

I've been struggling to get my head around a natural way of using TryParse because I keep expecting it to work the other way around (i.e. to return the parsed value and emit the boolean for whether the input parsed).
For example, if we take a basic implementation of Parse, the return value is the parsed input:
int parsedValue = int.Parse(input);
This works fine until it gets a value that it can't parse, at which point it entirely reasonably throws an exception. To me, the option then is either to wrap the parse in something like a try-catch block to handle the exception and a condition to set a default, or just to use TryParse to let C# do all that for me. Except that's not how TryParse works. The above example now looks like this:
bool parseSucceeded = int.TryParse(input, out int parsedValue);
To get it to assign in the same way as Parse, I wrap it in a ternary conditional with parsedValue and a default value (in this case, 0) as the true and false results respectively:
int parsedValue = int.TryParse(input, out parsedValue) ? parsedValue : 0;
But I still feel like I'm missing the point with TryParse if I'm just working around its default behaviour like this. I've read Tim Schmelter's excellent answer in which he shows its internal workings, from which I can suppose that it returns the boolean because it's easier internally than passing it out at all the various places that it currently returns. But I'm not sure about this, and I'm not satisfied that I understand its intent correctly. I also tried reading the documentation for it, but the remarks don't clear up my confusion (I don't think they even make its differences with Parse clear enough, like the change in return type).
Am I understanding it correctly, or am I missing something?
Sure, it could have been implemented as
int TryParse(string input, out bool succeeded)
{
}
But as mentioned in a comment, the common use case for the function is:
string input;
int parsedValue;
if(int.TryParse(input, out parsedValue))
{
// use parsedValue here
}
With the signature you propose, that code would now be:
string input;
bool succeeded;
int parsedValue = int.TryParse(input, out succeeded)
if(succeeded)
{
// use parsedValue here
}
So there's more code for no functional benefit. Also, with your ternary operator, if the parse fails you just set a value of zero, which is unnecessary since the default value of it is 0. You could just do:
int parsedValue;
int.TryParse(input, out parsedValue);
If the parse fails, parsedValue will have a value of 0; (I also question if/how you distinguish between an actual result of 0 and a failed parse, but I'm sure you have a reason).
So there's no technical reason why the signature is the way it is; it's a design decision that is appropriate for the most common use cases.
Of course, now with tuples in C# 7 you could have:
(int parsedValue, bool succeeded) = int.TryParse(input);
but again there's little functional benefit and prevents you from inlining the TryParse in an if statement.
Because logically you would want to check that the TryParse succeeded before trying to use the out value.
So this is more concise:
if (int.TryParse(input, out int parsedValue)}
{
// Do something with parsedValue
}
Than this:
int parsedValue = int.TryParse(input, out bool succeded);
if (succeeded)
{
// Do something with parsedValue
}
I think, a large part of your confusion stems from the method name isn't named exactly right:
int parsedValue = int.Parse("42");
This makes perfect sense, give me the integeger representation of a string.
int parsedValue = int.TryParse(input);
This makes sense as an extension of the concept: Input might be '42' or 'Oswald', but if it's a number I want that number.
In 2020, I think a better name would be CanParse(string input, out int result).
It better matches style guides and naming conventions, where returning a bool should be named with Is, Has, or Can.
It better matches how we use TryParse 99% of the time:
if (int.CanParse(input, out int result))
{
return result * 10;
}
But where I feel the current name makes sense, is the problem I assume it was trying to solve: To get rid of the following boilerplate code:
int result;
bool hasValidNumber = false;
try
{
result = int.Parse(input);
hasValidNumber = true;
}
catch
{
// swallow this exception
}
if (hasValidNumber)
{
// do things with result
}
else
{
// use a default or other logic
}

How do I write a function that applies the "+" operator to a collection of generic values?

I've got a function that's supposed to add up a bunch of generics, if possible.
Otherwise, it returns the value of the last generic it saw.
I'd like to loop through my list of generics, try adding them, and then catch an exception if/when they can't be added.
I understand that you can't try any opperators on a generic, but I can't understand why.
Isn't attempting a certain method that may fail exactly why try catch was build for?
I'm pretty sure there isn't an easy way around this, but if there is, let me know.
Also, the offending code:
T getValueAtTime(float time)
{
T toReturn = officalValue.Value;
float maxValue;
velocities.Sort();
foreach(ValueAtTime<T> toAdd in velocities)
{
if(toAdd.AtTime < time)
{
try
{
toReturn += toAdd.Value;
}
catch(OpperatorUnavailableError err)
{
toReturn = toReturn + toAdd.Value;
}
catch(Exception ex)
{
toReturn = toAdd.Value;
}
}
}
return toReturn;
}
Regardless of c#'s specific prohibition on try-catch in a generic, try catch should not be part of your standard operating method. Your code relies on try-catch in order to overcome an obstacle. That is utterly the wrong use of it. Try-catch is meant to test operations that might fail for uncontrollable (or at least unpredictable) circumstances, and shut down or retry that operation. It is extremely expensive for managed code to catch the error, and it's not meant to be a logical control mechanism.
Edit I did come up with an alternative, based on your comments explaining your question. You are operating on varying game objects. That doesn't require a generic; it requires an interface. If all your objects implement the interface IhasValueAtTime with a method float getValueAtTime(float time), then you can create a function like so float addTwoGetValueAtTimeObjectsSum(IhasValueAtTime item1, IhasValueAtTime item2)
I think the problem is that you are expecting different behaviour from
toReturn += toAdd.Value and toReturn = toReturn + toAdd.Value. They are (almost) exactly the same. See this link for further detail.
So when your try throws an exception, your catch will throw the same exception. I think that you would do better to do something like.
T toReturn = officalValue.Value;
float maxValue;
velocities.Sort();
foreach(ValueAtTime<T> toAdd in velocities)
{
if(toAdd.AtTime < time)
{
try
{
toReturn += toAdd.Value;
}
catch(OpperatorUnavailableError err)
{
toReturn = toAdd.Value;
break;
}
}
}
return toReturn;
I suppose your T is a generic parameter to a class/struct which contains your method. Now, I don't know what generic constraints you put on T, but is not possible to constrain T to only types which overload the + operator.
Therefore, this can not be done if T is a generic parameter.
What types are you using for T? Simple types like int, double and decimal which have "native" support for + in the language, or user-defined types which overload the + operator?

Check if calculation exceeds MaxValue

I currently got the following method, which is returning me percent-values. For example for an item-price of $350,000 and a percentage of 7%, it returns 24,500.
public static decimal GetPercentValue(decimal? percentage, decimal baseValue)
{
decimal result = 0m;
if (percentage != null)
{
try
{
result = Convert.ToDecimal(baseValue * percentage / 100m);
}
catch (OverflowException)
{
result = 0;
Logger.Warn("OverflowException caught in GetPercentValue() - should better be handled UI-Sided!");
}
}
return result;
}
I don't think this is handled the right way, so is there any way to avoid an exception in this situation?
An OverflowException is being thrown when a user enters an insane number like 999,999,999,999,999,999 and calculates 9999999999% of it. This way I can't check percentage or baseValue for <= decimal.MaxValue simply because they aren't... The calculation result itself then exceeds the decimal range.
This is an old question, but I ran into a similar issue, and thought to provide a possible alternate solution. The problem happens when some calculation of two numbers produces a number greater than a MaxValue. This causes an exception, and is hard to test in the usual way:
decimal existingValue = decimal.MaxValue;
decimal newValue = (decimal)100;
//doesn't work -- exception thrown here
if(existingValue + newValue <= decimal.MaxValue)
{
}
The solution that seems to work for me (without using a Try-Catch block) is to rewrite the equation, in this case as a subtraction:
if(decimal.MaxValue - existingValue >= newValue)
{
//DoSomething
}
MaxValue isn't exceeded because of the subtraction. I haven't tried a multiplication/division example, but I'm guessing it would work too.
The error handling should (most likely) be done outside the method. Right now you're hiding exceptions and returning wrong results (0 is returned when an error occures). The caller of your method cannot tell if the result is correct or if it's due to an OverflowException.
I'd rewrite the method like that:
public static decimal GetPercentValue(decimal? percentage, decimal baseValue)
{
if (percentage == null)
return 0;
return baseValue*(percentage.Value/100);
}
And optionally add a validation method that the user can call to check the parameters before calling the real method.. validation errors could be displayed in the UI:
public static string ValidatePercentValue(decimal? percentage, decimal baseValue)
{
try
{
GetPercentValue(percentage, baseValue);
return null;
}
catch (Exception ex)
{
return ex.Message;
}
}
Besides that note that...
baseValue*(percentage.Value/100)
... is better than...
baseValue*percentage.Value/100
Try to calculate 100% of decimal.MaxValue. The first one works while the second one throws an OverflowException.

TryParse pattern / Non Default constructor with readonly fields

How do people generally implement a parsing constructor with the TryParse pattern, when they have readonly backing fields, and a non default constructor, that would normally do the parsing?
Below is a contrived example of what I'm talking about, and the pattern I've settled on, but it seems clunky. In reality some of the types have a large number of properties. Sure, I can create a method that would take n ref arguments, do the parsing, and wire them up that way, but having a method with 15 arguments in some cases is a pain/smelly also.
The idea of two constructors, plus having to copy the result of the try parse to the readonly fields in the parsing constructor smells a little.
Anyone else have a better pattern?
Edit: Provide some more context
What I'm attempting to do, is refactor a large(ish) codebase, which has many types like the example below, where there is parsing of string arguments supplied to the constructor. Right now, all of the code uses constructor parsing, and the logic for this parsing is all done in the constructor. Messy and troublesome.
First thing I want to do, is move this code out of the constructor, into a factory method, (TryParse), but preserve the constructor signature, so I dont have lots of changes to the codebase. Long term, something better can be done when there is time.
Currently, the difficulty is keeping the constructure signature intact for the existing code, while allowing new code to use the TryParse pattern, and keep the readonly fields. If I relaxed the readonly fields, the entire process would be easier, but I'd rather not.
public class Point
{
private readonly float x, y;
public float X { get { return x; } }
public float Y { get { return y; } }
public Point(string s)
{
Point result;
if (TryParse(s, out result))
{
this.x = result.x;
this.y = result.y;
}
else
{
throw new System.ArgumentException("cant parse");
}
}
private Point(float x,float y) // for the sake of the example, this wouldnt have any use as public
{
this.x = x;
this.y = y;
}
public static bool TryParse(string s,out Point result)
{
var numbers = s.Split(',');
if(numbers.Length == 2)
{
result = new Point(float.Parse(numbers[0]),float.Parse(numbers[0]));
return true;
}
else
{
result = null;
return false;
}
}
}
Your current approach doesn't really work - because float.Parse can throw an exception. I'd use something like:
public static bool TryParse(string s, out Point result)
{
var numbers = s.Split(',');
if (numbers.Length == 2)
{
float x, y;
if (float.TryParse(numbers[0], out x) &&
float.TryParse(numbers[1], out y))
{
result = new Point(x, y);
return true;
}
}
result = null;
return false;
}
As StriplingWarrior says, I'd get rid of the parsing constructor to start with - if you're using TryParse anyway, add a Parse method too.
The idea of two constructors, plus having to copy the result of the try parse to the readonly fields in the parsing constructor smells a little.
Well with this approach, you only need one constructor - but what's wrong with passing values to a constructor and it copying them into the object? That seems natural to me.
Alternatively, you could use the approach we use in Noda Time where you create a whole separate object responsible for parsing and formatting, and a ParseResult<T> type which is able to represent the success/failure of a parse, while retaining the ability to throw an exception with meaningful information about the failure. Personally I find it a lot nicer than the BCL pattern, although arguably I'm biased :)
I usually try to avoid parsing constructors. There is a popular sentiment that constructors should do as little as possible, and usually only take arguments that get stored directly into fields for later use. If you want to parse a string, that's not the responsibility of the constructor.
You have a TryParse method that follows the typical expected pattern for C#/.NET apps. Make the changes that Jon Skeet recommends, then expect your users to call that method directly if they want to parse a string to a Point.

C# out parameters vs returns

So I am new to C# and I am having difficulty understanding out. As opposed to just returning something from a function
using System;
class ReturnTest
{
static double CalculateArea()
{
double r=5;
double area = r * r * Math.PI;
return area;
}
static void Main()
{
double output = CalculateArea();
Console.WriteLine("The area is {0:0.00}", output);
}
}
compare to this
using System;
class ReturnTest
{
static void CalculateArea(out double r)
{
r=5;
r= r * r * Math.PI;
}
static void Main()
{
double radius;
CalculateArea(out radius);
Console.WriteLine("The area is {0:0.00}",radius );
Console.ReadLine();
}
}
The first one is how I would generally do it. Is there a reason why I may want to use out instead of just a return statement? I understand that ref allows for 2 way communication, and that I generally shouldn't use ref unless the function is doing something with the variable I am sending it.
However is there a difference between out and return statements, like shown above? Syntax-wise is there a reason to favor one or the other?
A good use of out instead of return for the result is the Try pattern that you can see in certain APIs, for example Int32.TryParse(...). In this pattern, the return value is used to signal success or failure of the operation (as opposed to an exception), and the out parameter is used to return the actual result.
One of the advantages with respect to Int32.Parse is speed, since exceptions are avoided. Some benchmarks have been presented in this other question: Parsing Performance (If, TryParse, Try-Catch)
The out keyword is mostly used when you want to return more than one value from a method, without having to wrap the values in an object.
An example is the Int32.TryParse method, which has both a return value (a boolean representing the success of the attempt), and an out parameter that gets the value if the parsing was successful.
The method could return an object that contained both the boolean and the integer, but that would need for the object to be created on the heap, reducing the performance of the method.
Only time I tend to use out is when I need multiple things returned from a single method. Out lets you avoid wrapping multiple objects into a class for return. Check out the example at the Microsoft Out page.
You can have multiple out parameters, so if you need to return multiple values, it's a bit easier than creating a special class for your return values.
When one variable is concerned out and return are OK. But what if you wanted to return more than 1 values? Out helps in that.
static void CalculateArea(out double r, out double Foo)
{
//Can return 2 values in terms of out variables.
}
static double CalculateArea(double r)
{
// Will return only one value.
}

Categories