Home / Questions / If your program needs to read integers, but the user entered strings, an error wouldoccur when running this program. What kind of error is this?
Explanatory Question

If your program needs to read integers, but the user entered strings, an error wouldoccur when running this program. What kind of error is this?

👁 4,288 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

Runtime error.

This is a runtime error, also known as an exception. When the program is running and tries to convert a string input to an integer, but the string cannot be converted to an integer, it will raise an error.

Example Java

Here is an example of a runtime error in Java due to user inputting a string instead of an integer:


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter an integer: ");
    try {
      int num = Integer.parseInt(sc.nextLine());
      System.out.println("You entered: " + num);
    } catch (NumberFormatException e) {
      System.out.println("Error: You did not enter an integer.");
    }
  }
}

In this example, if the user inputs a string instead of an integer, the Integer.parseInt() method will raise a NumberFormatException error. The code in the catch block will then be executed, printing out an error message indicating that the user did not enter an integer.

Example Python

Here's an example of the error in Python:


age = input("Enter your age: ")
print("Your age is:", age)

If the user enters a string instead of an integer, a ValueError will be raised when the code tries to convert the string to an integer:


Enter your age: twenty
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'twenty'