Reputation: 1073
I've checked this code several times and I cannot figure out why it's spitting back errors in regards to the catch statement. I'm aware that handling multiple exception with one catch clause is possible with Java 7.
import java.io.*;
import java.util.*;
public class MultiCatch
{
public static void main(String[] args)
{
int number;
try
{
File file = new File("Numbers.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext())
{
number = inputFile.nextInt();
System.out.println(number);
}
inputFile.close();
}
catch(FileNotFoundException | InputMismatchException ex)
{
System.out.println("Error processing the file.");
//System.out.println("Error processing the file." + ex.getMessage());
}
}
}
Error:
$ javac MultiCatch.java
MultiCatch.java:25: <identifier> expected
catch(FileNotFoundException | InputMismatchException ex)
^
MultiCatch.java:25: '{' expected
catch(FileNotFoundException | InputMismatchException ex)
^
MultiCatch.java:25: not a statement
catch(FileNotFoundException | InputMismatchException ex)
^
MultiCatch.java:25: ';' expected
catch(FileNotFoundException | InputMismatchException ex)
^
MultiCatch.java:31: reached end of file while parsing
}
^
5 errors
If it makes a difference I'm on a OSX 10.8 running Java 7.
Upvotes: 1
Views: 8100
Reputation: 21728
This code has no errors and is Java 7 compliant. Check the settings of your compiler, you are compiling the code as Java 6.
Upvotes: 1
Reputation: 10697
Depending on your IDE set the Java compatibility level from 1.6 or 1.5 to 7.
Upvotes: 0
Reputation: 178253
Under Java 6, I get this compiler error with your code:
C:\dev\src\misc\MultiCatch.java:25: <identifier> expected
catch(FileNotFoundException | InputMismatchException ex)
^
C:\dev\src\misc\MultiCatch.java:25: '{' expected
catch(FileNotFoundException | InputMismatchException ex)
^
C:\dev\src\misc\MultiCatch.java:25: not a statement
catch(FileNotFoundException | InputMismatchException ex)
^
C:\dev\src\misc\MultiCatch.java:25: ';' expected
catch(FileNotFoundException | InputMismatchException ex)
^
C:\dev\src\misc\MultiCatch.java:31: reached end of file while parsing
}
However, under Java 7, your code compiles successfully.
You must have been using Java 6 or below to get those errors.
The problem is not that each exception must have a name. Under Java 7,
catch(FileNotFoundException | InputMismatchException ex)
is correct syntax.
Upvotes: 3