-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);
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 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. – khelwood Feb 12 '21 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... – rkosegi Feb 12 '21 at 15:34
  • Does this answer your question? (https://stackoverflow.com/questions/2448843/variable-might-not-have-been-initialized-error) – AKSingh Feb 12 '21 at 15:36
  • Use the methods on `Scanner` to check if the input is an int, and remove the try-catch. – Mark Rotteveel Feb 12 '21 at 15:37

1 Answers1

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.

Shan
  • 15
  • 1
  • 8