Can Genc
Can Genc

Reputation: 15

using nested try statement in java

I have some problem with the nested try statements in java and I am asked to use try nested statements instead of if()

here is the some part of the code which I need to use nested try statement

 public Date subtractYear() throws Exception
  {
    if (day == 29 && month == 2)
      return new Date(28, month, year - 1);
    else
      return new Date(day, month, year - 1);
  }

Upvotes: 1

Views: 634

Answers (1)

Ryan Ransford
Ryan Ransford

Reputation: 3222

The above code is wrong at best and dangerous at worst. There are reasons why the Date and Calendar classes exist. Managing leap years is one of them.

The above code should only see production in cases where you really understand what you are doing and need to achieve performance by this means. Your best bet is as follows:

public Date subtractYear() {
  final Calendar c = new Calendar();
  c.set(year, month, day); // set your class's "current" date
  c.add(Calendar.YEAR, -1); // remove 1 year
  return c.getTime(); // get the Date object back from the Calendar
}

As an additional comment, using try-catch blocks for handling normal program flow is typically a bad way to handle things which you are expecting on a normal basis. The generation of exception stack traces is a costly operation.

Upvotes: 4

Related Questions