user5582406
user5582406

Reputation:

Error catching in a java class

I having a problem with catching errors on my android application. It's just meant for practice but here is the following issue:

I have a class which takes the values from the screen and text boxes. It then converts them into a day class which has a Start, Break , and Finish.

The GetHours() method then splits a value such as 12:30 into 12 and .5 (12.5) and feeds back how many hours are worked with a simple formula HoursWorked = (Finish - Start) - Lunch;

My question is if i use a class like this will i be able to catch an error such as starting work at 45:78 (impossible) and if so where do i catch the error in the main activity or in the class?

Any help is Appreciated!

Upvotes: 1

Views: 72

Answers (2)

gkgkgkgk
gkgkgkgk

Reputation: 717

You should throw the error where the calculation is being made. Do a check after calculating that the time is valid and return it if it is. If it isn't, throw an exception. The object calling for this number can then be surrounded with try/catch, and throw the error that says that the number is invalid

Example:

// in getHours() :

double hours = 12.5;

if(hours < 13) { //check to make sure hours is valid/correct
    return hours;
}
else{
    throw new Exception("Hours value of " + hours + " is not valid");
}

// in main class:

try{
    hours = getHours();
}
catch(Exception e){
    e.printStackTrace();
}

Upvotes: 1

Krishna Sharma
Krishna Sharma

Reputation: 2877

Looks like your logic is wrong while converting time in format hour:min, for example output of "starting work at 45:78" should be 46:18. I would suggest you to look at the logic of method getHour and correct the calculation instead of thinking to consider value 45:78 as error.

Upvotes: 0

Related Questions