Code to handle Exceptions
In the preceding steps, we did not handle the exception when an invalid input is provided from the user. In this step, we will handle any exception by using the try-catch
block.
import java.util.Scanner;
import java.lang.*;
public class LongToString {
public static String convertLongToString(long l, int r) {
String s = Long.toString(l, r);
return s;
}
public static void main(String[] args) {
try {
System.out.println("Enter a long value and a radix: ");
Scanner sc = new Scanner(System.in);
long num = sc.nextLong();
int radix = sc.nextInt();
System.out.println(convertLongToString(num, radix));
} catch (Exception e) {
System.out.println("Invalid input. " + e.getMessage());
}
}
}