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);
try/catchis a branch. You have created a branch in your code in whichnum1is not initialised, because an exception happened and the execution jumped to the catch block.num1can't be parsed into integer you print error and then continue. Compiler clearly points out what's wrong...Scannerto check if the input is an int, and remove the try-catch.