Error:
'else' without 'if'
Explanation:
The compiler has found an else keyword without a corresponding if condition. The compiler attempts to match else keywords with the closest previous if condition that does not already have a matching else.
Checklist:
- Is there a semicolon after an if condition? If so, remove the semicolon.
- Is a curly brace missing? Is there an open curly brace, {, for the if statement's true or false block without a corresponding closing curly brace, }?
- Does the true or false block for an if condition contain more than one statement? If so, verify that curly braces begin and end the block.
Examples:
1. With the following statements in a source file named Average.java:
12 if ( count == 0 ); // Note: semicolon incorrect here
13 System.out.println( "Cannot divide by 0" ):
14 else
15 average = total / count;
the Java compiler would generate the following error:
Average.java:14: 'else' without 'if'
else
^
To fix this problem, remove the semicolon in line 12.
2. Similarly, with the following statements in a source file named Average.java:
12 if ( count == 0 )
13 { // Note: open curly brace without a matching closing curly brace
14 System.out.println( "Cannot divide by 0" ):
15 else
16 average = total / count;
the Java compiler would generate the following error:
Average.java:15: 'else' without 'if'
else
^
To fix this problem, either remove the open curly brace in line 13 or insert a closing curly brace before line 15.
3. Finally, with the following statements in a source file named Average.java:
12 if ( count == 0 )
13 System.out.println( "Cannot divide by 0" ):
14 System.out.println( "Operation aborted" );15 else
16 average = total / count;
the Java compiler would generate the following error:
Average.java:15: 'else' without 'if'
else
^
In this code, the true block of the if condition contains two statements. However, without curly braces, the compiler considers only line 13 to be the true block. To fix this problem, add an open curly brace before line 13 and a closing curly brace before line 15.