Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an elegant way to try catch properties in C#

What's an elegant way to refactor this code?

Say, I have the following object

public class SomeObject
{
    public SomeInnerObject1 Cat { get; set; }
    public SomeInnerObject2 Dog { get; set; }

    public class SomeInnerObject1
    {
        public int Age { get; set; }

        public string AgeAsString
        {
            get
            {
                if(Age < 0 )
                    throw new Exception();

                return Age.ToString();
            }
        }
    }

    public class SomeInnerObject2
    {
        public string BirthDayString { get; set; }
        public DateTime BirthDay { get { return DateTime.Parse(BirthDayString); } }
    }
}

And say, I have to set a few textboxes's values that I need to set

var obj = new SomeObject
          {
              Cat = new SomeObject.SomeInnerObject1 {Age = -1},
              Dog = null
          };

//These will pass but it looks ugly
try
{
    textbox1.Text = obj.Dog.BirthDay.Month.ToString();
}
catch{ }

try
{
    textbox2.Text = obj.Cat.AgeAsString;
}
catch { }

//These will fail
textbox1.Text = obj.Dog.BirthDay.Month.ToString();
textbox2.Text = obj.Cat.AgeAsString;

Is there a better way to do this?

Thanks,

Chi

like image 323
Chi Chan Avatar asked Jun 08 '11 15:06

Chi Chan


People also ask

How do you use try catch?

The “try… It works like this: First, the code in try {...} is executed. If there were no errors, then catch (err) is ignored: the execution reaches the end of try and goes on, skipping catch . If an error occurs, then the try execution is stopped, and control flows to the beginning of catch (err) .

Can we use catch () without passing arguments in it?

You can also omit the arguments on the catch block entirely. In this case, the catch block will catch all exceptions, regardless of their type. Because you don't declare an exception variable, however, you won't have access to information about the exception.

What is the use of properties in C sharp?

Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code. A get property accessor is used to return the property value, and a set property accessor is used to assign a new value.

What is a try catch statement?

Java try and catch The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.


2 Answers

When I really don't care what happens for a particular line of code, I do something like this:

ExecuteIgnoringExceptions(() => textBox.Text = Some.Possibly.Bad.Value);

void ExecuteIgnoringExceptions(Action a) 
{
    try
    {
        a.Invoke();
    }
    catch
    {
    }
}
like image 107
Kaleb Pederson Avatar answered Nov 14 '22 21:11

Kaleb Pederson


I would start by moving the Int check from the get to the set property. If it isn't supposed to be less than 0, then don't let it get set to less than 0. For the date, use a TryParse method in the setter to make it exception safe. Then make sure that use a private setter in the BirthDay property.

public class SomeObject
{
    public SomeInnerObject1 Cat { get; set; }
    public SomeInnerObject2 Dog { get; set; }

    public class SomeInnerObject1
    {
        private int _Int = 0;
        public int Int {
            get
            {
                return _Int;
            }
            set
            {
                if(value < 0) 
                    throw new Exception("Int must be greater than or equal to 0.");
                else
                    _Int = value;
            }
       }

        public string String
        {
            get
            {
                return Int.ToString();
            }
        }
    }

    public class SomeInnerObject2
    {
        private string _BirthDayString = "";
        public string BirthDayString
        {
            get
            {
                return _BirthDayString;
            }
            set
            {
                DateTime newDate;
                if(DateTime.TryParse(value, newDate))
                    BirthDay = newDate;
                else
                    throw new ArgumentException("Birthday string must be a properly formatted date.");
            }
        }

        private DateTime _BirthDay = DateTime.MinValue;
        public DateTime BirthDay
        {
            get 
            {
                return _BirthDay;
            }
            private set
            {
                _BirthDay = value;
            }
        }
    }
}

The main point being that values should be validated on the way in rather than on the way out.

like image 22
Joel Etherton Avatar answered Nov 14 '22 23:11

Joel Etherton