Validating data to nest if or not within try and catch
Posted
by
Skippy
on Programmers
See other posts from Programmers
or by Skippy
Published on 2013-10-29T11:37:58Z
Indexed on
2013/10/29
16:12 UTC
Read the original article
Hit count: 299
I am validating data, in this case I want one of three ints. I am asking this question, as it is the fundamental principle I'm interested in. This is a basic example, but I am developing best practices now, so when things become more complicated later, I am better equipped to manage them.
Is it preferable to have the try and catch followed by the condition:
public static int getProcType()
{
try
{
procType = getIntInput("Enter procedure type -\n"
+ " 1 for Exploratory,\n"
+ " 2 for Reconstructive, \n"
+ "3 for Follow up: \n");
}
catch (NumberFormatException ex)
{
System.out.println("Error! Enter a valid option!");
getProcType();
}
if (procType == 1 || procType == 2 || procType == 3)
{
hrlyRate = hrlyRate(procType);
procedure = procedure(procType);
}
else
{
System.out.println("Error! Enter a valid option!");
getProcType();
}
return procType;
}
Or is it better to put the if within the try and catch?
public static int getProcType()
{
try
{
procType = getIntInput("Enter procedure type -\n"
+ " 1 for Exploratory,\n"
+ " 2 for Reconstructive, \n"
+ "3 for Follow up: \n");
if (procType == 1 || procType == 2 || procType == 3)
{
hrlyRate = hrlyRate(procType);
procedure = procedure(procType);
}
else
{
System.out.println("Error! Enter a valid option!");
getProcType();
}
}
catch (NumberFormatException ex)
{
System.out.println("Error! Enter a valid option!");
getProcType();
}
return procType;
}
I am thinking the if within the try, may be quicker, but also may be clumsy. Which would be better, as my programming becomes more advanced?
© Programmers or respective owner