-2

When I try to use a try catch exception handler in my code, I'm getting the error message:

java: variable num1 might not have been initialized

The code seems to work when I initialize num1 as num1 = 0. Is there any technique to use try catch by just initializing int num1? Why do I get the error?

Code snippet:

import java.util.Scanner; public class Calculator { public static void main(String[] args) { int num1, num2, ans; String operator; Scanner scn1 = new Scanner(System.in); Scanner scn2 = new Scanner(System.in); //Getting first number try { System.out.print("Enter your first number : "); num1 = scn1.nextInt(); } catch(Exception e) { System.out.println("Enter an integer!"); } //Getting second number System.out.print("Enter the second number : "); num2 = scn1.nextInt(); //Getting operator System.out.print("Enter an operator(+, -, *, /) : "); operator = scn2.nextLine(); //test System.out.println("First number : " + num1); System.out.println("Second number : " + num2); System.out.println("Operator : " + operator); 
4
  • A try/catch is a branch. You have created a branch in your code in which num1 is not initialised, because an exception happened and the execution jumped to the catch block. Commented Feb 12, 2021 at 15:34
  • 3
    Your control flow is just broken. If num1 can't be parsed into integer you print error and then continue. Compiler clearly points out what's wrong... Commented Feb 12, 2021 at 15:34
  • Does this answer your question? (stackoverflow.com/questions/2448843/…) Commented Feb 12, 2021 at 15:36
  • Use the methods on Scanner to check if the input is an int, and remove the try-catch. Commented Feb 12, 2021 at 15:37

1 Answer 1

0

There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.