• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Need help with file imports with Java

d3lt4

Senior member
Ok, I just have one error when I run this. I have code to read in numbers to an array from a file, but I keep getting an error saying "
F:\CS\test3\src\test3\Main.java:24: unreported exception java.lang.Exception; must be caught or declared to be thrown
matrix1 = input(matrix1);"

Here is the code for the method:
public static int[][] input(int[][] a)throws Exception{
int[][] array;
java.io.File file = new java.io.File ("in.dat");
if (!file.exists()){
JOptionPane.showMessageDialog(null, "FILE DNE");
System.exit(0);
}
java.util.Scanner input = new java.util.Scanner(file);
while (input.hasNextInt()){
for (int i = 0; i< a.length; i++){
for (int j=0; j< a[0].length; j++){
array[j] = input.nextInt();
}
}
input.close();
}
return array;
}


This is up in main where I am getting the error:
int[][] matrix1;
int[][] matrix2;
int sixes;
String output = "";
matrix1 = create(5,7);
<matrix1 = input(matrix1);

That is the part giving me an error.

Please help, thanks.

 
nvmnd, I got it to work.
Apparently I had to add "throws Exception" after public static main...
 
well. . .that's one way but probably not really the ideal way in this case. I think what the compiler is trying to tell you is that the input() method you are calling is declared in such a way that it throws an Exception. Whatever code calls that input() method must either declare that it throws that same exception (or some superclass of that exception) if it does not handle that exception itself. But what you probably want to do is catch that exception in this case and handle it properly. So the "better" way to fix the code in your case would have been:

try { matrix1 = input(matrix1); } catch (Exception e) { //code to handle the exception here }

In the catch block of the exception handling code you could either print some meaningful message to the user about what was wrong, or try to recover if possible and continue execution. That is not to say that you never want to just throw exceptions and let them bubble up through the stack. . .sometimes that is perfectly fine depending on the circumstances. . .maybe you want to have all exception handling abstracted to a certain layer of your code or something, who knows? But in your case you probably want a try/catch block. Then your main() method does not need to be declared to throw any exception because you are handling it.
 
Back
Top