-4
import java.util.Scanner;
import java.util.InputMismatchException;



public class divide {
    public static void main(String[] args) {
        Scanner kb = new Scanner (System.in);
        int a,b;

        try{
            System.out.println("enter 2 number ");
            a = kb.nextInt();
            b = kb.nextInt();
            int c = a/b;
            System.out.println("div="+c);

        }
        catch(ArithmeticException e)
        {
            System.out.println("please enter non 0 in deno");
        }
        catch (InputMismatchException e2)
        {
            System.out.println("please input int only");
            System.exit(0);

        }
        int d= a+b;
        System.out.println("sum="+d);
    }
}

error

divide.java:38: error: variable a might not have been initialized int d= a+b; ^ divide.java:38: error: variable b might not have been initialized int d= a+b;

  • 1
    The compiler does not approve your question title – wero Mar 21 '16 at 19:00
  • 2
    Local variable do not have initial values. You must initialize the variable with some value. Refer this link http://www.tutorialspoint.com/java/java_variable_types.htm – Vighanesh Gursale Mar 21 '16 at 19:00
  • This has nothing to do with try/catch. You're simply not initializing your variables, so the compiler can't guarantee that they will be initialized when you're using them. – David Mar 21 '16 at 19:04

3 Answers3

2

You need to initialize you variable

int a =0,b=0;
Denis
  • 1,219
  • 1
  • 10
  • 15
1

Remember, the way a try/catch block works, there's no guarantee that the statements inside it actually get run. (Because there could be an error, resulting in them just getting skipped.)

Because of that, Java can't guarantee that a and b have been defined, when you try to reference them. In this case they always will have been, because you're exiting in the catch statement.

You can solve this by giving them initial default values, or moving the referencing code into the try block.

Edward Peters
  • 3,623
  • 2
  • 16
  • 39
1

If your try-catch fails no matter why/how when reading a, then the variable b is never initialized... the app jumps to the catch block, and at the end you do:

int d= a+b;
System.out.println("sum="+d);
    

What is supposed to be the value of b in that case??

the quick fix is:

declare and init the variables...

Scanner kb = new Scanner (System.in);
int a = 0;
int b = 0;
        
Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97