Need help with file imports with Java

d3lt4

Senior member
Jan 5, 2006
848
0
76
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.

 

d3lt4

Senior member
Jan 5, 2006
848
0
76
nvmnd, I got it to work.
Apparently I had to add "throws Exception" after public static main...
 

ahurtt

Diamond Member
Feb 1, 2001
4,283
0
0
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.
 

tfinch2

Lifer
Feb 3, 2004
22,114
1
0
The File constructor and exists() method both throw exceptions. Those need to be caught.