I'm trying to write following class:
public class Secteur {
private final static int num_secteur;
static{
try {
num_secteur = SecteurDAO.getCurrNumSecteur();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
But I'm having following warning :
The blank final field num_secteur may not have been initialized
The SecteurDAO.getCurrNumSecteur()
method accesses the database in order to get the integer that will be set to num_secteur field.
What is the problem with my code ?
The call to
SecteurDAO.getCurrNumSecteur()
might fail (throw an exception) and thus there's no value to assign tonum_secteur
. Hence it might not be initialized in case of an exception.To fix that you might either want to initialize it with some special value (e.g. -1) or set that value in the catch-block.
Oh, and remove the
final
keyword, otherwise you'd get the error message "The final field num_secteur may already have been assigned". That's because you can only ever assign a value to a final field once and even if you know that assignment can't happen in case of an exception (because the exception will be thrown before) the compiler can't know that for sure and hence tells you that the variable might have been already assigned.