Java で変数が有効な整数かどうかをチェックするための 2 つのスタイルを見てきました。1 つは、実行してInteger.parseInt結果の例外をキャッチします。もう1つは、パターンを使用することです。次のうちどれがより良いアプローチですか?
String countStr;
int count;
try {
    count = Integer.parseInt(countStr);
} catch (Exception e) {
    //return as the variable is not a proper integer.
    return;
}
また
String integerRegex = "([0-9]{0,9})";
if (countStr.isEmpty() || !Pattern.matches(integerRegex, countStr)) {
    //return as the variable is not a proper integer.
    return;
}
ここでの私の質問は、Integer.parseInt()検証の標準的な方法を検証するための例外を実行してキャッチすることintですか? 私の正規表現が完璧ではないことは認めます。しかし、Java で int の検証に使用できる組み込みメソッドはありますか? 実際には、単に例外をキャッチするのではなく、何らかの検証を行った方がよいのではないでしょうか?