Number Format Exception Java Example Program


Syntax

try{
    //Do something
}catch(java.lang.NumberFormatException e){
    //Do something with the caught exception
}

NumberFormat Exception Example Program

public class NumberFormatException {
    static void numberConversion(String input){
        try{
            int number = Integer.parseInt(input);
            System.out.println("The input integer after conversion is : "+number);
        }catch(java.lang.NumberFormatException e){
            System.out.println("Error!!! While converting input to integer");
        }
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the string to be converted to an integer : ");
        String input = scanner.nextLine();
        numberConversion(input);
    }
}

Sample Output 1

Enter the string to be converted to an integer : 
the
Error!!! While converting input to integer

Sample Output 2 

Enter the string to be converted to an integer : 
12
The input integer after conversion is : 12