Handle invalid input using a try-catch
block.
public class LongParseLong {
public static void main(String[] args) {
String str = "abc";
try {
long num = Long.parseLong(str);
System.out.println("The string value " + str + " is converted to the long value " + num);
} catch (NumberFormatException e) {
System.out.println("Invalid input: " + str + " cannot be converted to a long");
}
}
}
In the above code, the string "abc"
is not a valid input for the parseLong
method, as it cannot be converted to a long value. Therefore, a NumberFormatException
is thrown. This exception is caught by the catch
block, which prints an error message to the console.