Unhandled Exception Type IOException [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why do I get the “Unhandled exception type IOException”?
I'm trying to solve Euler #8 using the following algorithm. Problem is, whenver I modify the line I have the giant comment on, the error Unhandled Exception Type IOException appears on each line that I've marked with the comment //###.
private static void euler8()
{
int c =0;
int b;
ArrayList<Integer> bar = new ArrayList<Integer>(0);
File infile = new File("euler8.txt");
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(infile), //###
Charset.forName("UTF-8")));
while((c = reader.read()) != -1) { //###
char character = (char) c;
b = (int)character;
bar.add(b); /*When I add this line*/
}
reader.close(); //###
}

Yes, IOException is a checked exception, which means you either need to catch it, or declare that your method will throw it too. What do you want to happen if the exception is thrown?
Note that you should generally be closing the reader in a finally block anyway, so that it gets closed even in the face of another exception.
See the Java Tutorial lesson on exceptions for more details about checked and unchecked exceptions.

One solution: change to
private static void euler8() throws IOException {
But then the calling method has to catch the IOException.
or catch the Exception:
private static void euler8()
{
int c =0;
int b;
ArrayList<Integer> bar = new ArrayList<Integer>(0);
BufferedReader reader;
try {
File inFile = new File("euler8.txt");
reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(infile), //###
Charset.forName("UTF-8")));
while((c = reader.read()) != -1) { //###
char character = (char) c;
b = (int)character;
bar.add(b); /*When I add this line*/
}
} catch (IOException ex) {
// LOG or output exception
System.out.println(ex);
} finally {
try {
reader.close(); //###
} catch (IOException ignored) {}
}
}

Wrap in a try/catch block to catch the Exceptions.
If you do not do that it will go unhandled.

What happens if you can't read the nominated file ? The FileInputStream will throw an exception and Java mandates that you'll have to check for this and handle it.
This type of exception is called a checked exception. Unchecked exceptions exist and Java doesn't require you to handle these (largely because they're unhandable - e.g. OutOfMemoryException)
Note that your handling may include catching it and ignoring it. This isn't a good idea, but Java can't really determine that :-)

Related

Use try-with-resources or close this "BufferedReader" in a "finally" clause in sonarqube

I was trying to implement this code but was getting some "Use try-with-resources or close this "BufferedReader" in a "finally" clause" in sonarqube i have already read other's answer but none of them helped me, so can anyone please guide me where exactly i have to do code changes(Really don't have any background for above error in sonarqube)
public static List getlockList(String componentPath) throws IOException
{
List<String> listOfLines = new ArrayList<String>();
BufferedReader bufReader = null;
try {
bufReader = new BufferedReader(new FileReader(componentPath));
String line = bufReader.readLine();
//Looking for the pattern starting with #(any number of #) then any String after that
Pattern r = Pattern.compile("(^[#]*)(.*)");
while (line != null) {
line = line.trim();
if(!("".equals(line)))
{
if(line.matches("^#.*"))
{
Matcher m = r.matcher(line);
if (m.find( ))
{
//System.out.println("Found value: " + m.group(2) );
unlockList.add(m.group(2).trim());
}
}
else
{
listOfLines.add(line);
//empty lines removed
}
line = bufReader.readLine();
}
else
{
line = bufReader.readLine();
}
}
} catch(Exception ex) {
log.info(ex);
} finally {
if (bufReader != null)
bufReader.close();
}
return listOfLines;
}
The BufferedReader should be created in a try-block similar to this:
public static List getlockList(String componentPath) throws IOException
{
List<String> listOfLines = new ArrayList<String>();
try(BufferedReader bufReader = new BufferedReader(new FileReader( componentPath)))
{
// do your magic
}
return listOfLines;
}
The Reader will be closed automatically even if an exception occur. There is also a description of the rule which covers a compliant solution: https://rules.sonarsource.com/java/tag/java8/RSPEC-2093
The whole logic for reading file lines must be surrounded with try catch block. This is because you can get exception like FileNotFoundException and so on. After you read the lines you have to close your buffer reader in final clause because if there is exception thrown then the BufferedReader might not be closed and you will have a memory leak problems.
You can use also try with resources which is new way of handling closable resources like BufferedReader. Then you do not need to call bufReader.close();
Here is oracle documentation with examples:
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

closing BufferedReader results in Stream closed in Junit

I have several JUnit tests, all of them are invoking the same class (with different inputs), and check for the return value of this class.
The class itself has a code that uses BufferedReader, that is being closed at the end of the read.
The first test is passing, but every test after it is throwing the Stream closed
I am creating a new instance of the class in each test, as well as a new BufferReader in the read code.
Aren't tests supposed to be contained? isn't a new instance should resolve this issue?
My Example Tests (omitted code that generates different args in each test for readability)
public void test1() {
float result = 0;
MyClass myClassInst = new MyClass();
result = myClassInst.Execute(args);
assert (result > 0.5);
}
public void test2() {
float result = 0;
MyClass myClassInst = new MyClass();
result = myClassInst.Execute(args);
assert (result > 0.5);
}
Within myClass I have the following code (INPUT_STREAM is a txt file in my project resources and is identical for every test)
ReadInputsClass re = new ReadInputsClass(INPUT_STREAM);
which invokes the following method
___EDIT_________
The way I am getting INPUT_STREAM is:
at the top of MyClass I have
private static InputStream INPUT_STREAM= initializeInputStream();
private static InputStream initializeInputStream() { InputStream inputStream = System.class.getResourceAsStream("textFile.txt"); return inputStream; }
___END EDIT_____
the ReadInputsClass constructor is calling the following code
private ArrayList<SomeClass> readStream(InputStream inputStream) {
ArrayList<SomeClass> ret = new ArrayList<SomeClass>();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(inputStream));
String line = br.readLine();
while (line != null) {
// do some stuff on the line just read
line = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
Clearly the issue is coming from the br.close in this code
when I put a break point, the 2nd test is getting to br that is set to null, creating a new br, and when it is reaching the br.readLine() it is throwing the stream close.
I do not understand why? Isn't the new br = new BufferedReader should start fresh?
You are nesting streams in your code:
br = new BufferedReader(new InputStreamReader(inputStream));
In Java, if you close the outer most stream, all other streams in the chain are closed as well. That means if you call br.close(), then the close() method on the InputStreamReader gets called which in turn calls the close method on your inputStream variable.
If you initialize INPUT_STREAM as a static variable and re-use it, that would mean subsequent tests using the INPUT_STREAM variable will use a stream that has already been closed.

Unreported exception java

I am getting an unreported exception; must be caught or declared to be thrown error in the fill method below. From similar posts I read I am assuming that the error originates since the read method has throws Exception but I cannot fix it.
public void read(int fileName) throws Exception
{
FileInputStream in = null;
try
{
Scanner in = new Scanner("dataset.txt");
File inFile = new File(in.nextLine());
in = new FileInputStream(inFile);
}
catch ( Exception e)
{
System.out.println(e);
}
BufferedReader buf = new BufferedReader(new InputStreamReader(in) );
String input;
input = buf.readLine();
fill(input,buf);
}
where fill is defined as:
public void fill(String in,BufferedReader buf)
{
StringTokenizer token = new StringTokenizer(input);
no = token.countTokens();
constraints = new Vector[noOfAttributes];
for (int i=0; i < no; i++)
{
c[i] = new Vector();
names = new String[noOfAttributes];
}
for (int i=0; i < no; i++)
{
names[i] = token.nextToken();
}
while((in = buf.readLine()) != null) //<----error given here
{
token = new StringTokenizer(input);
Train example = new Train(no);
}
buffer.close();
}
Your fillData calls buffer.readLine(), which is declared to throw IOException - but you neither catch the exception witin fillData, nor declare that it might be thrown.
The simplest fix is to change the signature of fillData to:
public void fillData(String input, BufferedReader buffer) throws IOException
I would also strongly recommend not closing the reader within fillData. Usually, the same code that acquires a resource should be responsible for closing it. A try-with-resources statement is most appropriate here, so in read:
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(in))) {
String input = buffer.readLine();
fillData(input,buffer);
}
Even this isn't ideal, however - because you're opening the input stream earlier on. I'd also recommend always passing an encoding to the InputStreamReader constructor, otherwise it will use the platform default encoding. In Java 7+ you can use Files.newBufferedReader which defaults to UTF-8.
Additionally:
read declaring that it throws Exception is generally a bad idea; only throw specific exceptions
Catching Exception in read is a bad idea; only catch specific exceptions
Continuing in read after a failure is a bad idea - in will be null, causing a failure immediately afterwards
It's very bizarre to have a parameter called fileName of type int. As it happens, you're not using that anyway - what's the point of it?
Basically all of your exception handling and resource management needs a fair amount of work.

Java error: Default constructor cannot handle exception type FileNotFound Exception

I'm trying to read input from a file to be taken into a Java applet to be displayed as a Pac-man level, but I need to use something similar to getLine()... So I searched for something similar, and this is the code I found:
File inFile = new File("textfile.txt");
FileInputStream fstream = new FileInputStream(inFile);//ERROR
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
The line I marked "ERROR" gives me an error that says "Default constructor cannot handle exception type FileNotFoundException thrown by implicit super constructor. Must define an explicit constructor."
I've searched for this error message, but everything I find seems to be unrelated to my situation.
Either declare a explicit constructor at your subclass that throws FileNotFoundException:
public MySubClass() throws FileNotFoundException {
}
Or surround the code in your base class with a try-catch block instead of throwing a FileNotFoundException exception:
public MyBaseClass() {
FileInputStream fstream = null;
try {
File inFile = new File("textfile.txt");
fstream = new FileInputStream(inFile);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
// Do something with the stream
} catch (FileNotFoundException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
try {
// If you don't need the stream open after the constructor
// else, remove that block but don't forget to close the
// stream after you are done with it
fstream.close();
} catch (IOException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
Unrelated, but since you are coding a Java applet, remember that you will need to sign it in order to perform IO operations.
You need to surround your code with try and catch as follows:
try {
File inFile = new File("textfile.txt");
FileInputStream fstream = new FileInputStream(inFile);//ERROR
} catch (FileNotFoundException fe){
fe.printStackTrace();
}
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
This is guesswork as we don't have the complete code.
From the Javadoc:
public FileInputStream(File file) throws FileNotFoundException
It means that when you do a new FileInputStream() like you do, it can come back with a FileNotFoundException. This is a checked exception, that you need to either rethrow (i.e. add 'throws FileNotFoundException' in the method where you do the new) or catch (see other try/catch responses).

java: Do I need to close all the streams?

I have a method that reads text from a file; decompression may be required, depending on an input parameter:
public static String readText(File inFile, boolean compressed) {
InputStream in = null;
InputStreamReader isr = null;
StringBuilder sb = new StringBuilder();//constant resizing is costly, so set the STRING_SIZE
try {
in = new FileInputStream(inFile);
if (compressed) {
in = new GZIPInputStream(in);
}
isr = new InputStreamReader(in);
int length = 0;
char[] cbuf = new char[8 * 1024];
while ((length = isr.read(cbuf)) != -1) {
sb.append(cbuf, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
return sb.toString();
}
It was suggested that I use InputStream like this so it is easier to write, and so that in the end I only have to close one thing. I am still a bit worried this might cause a memory leak. So my question is: does anyone knows if the code above is OK? Or do I have to get back to a dozen of streams and close them one by one in a finally block?
Thanks a lot.
Yes, closing the outermost stream/reader is sufficient.
However, your code has another potential bug: new InputStreamReader(in) will use the platform default encoding, which depends on the OS region/language settings. You should specify the encoding of the text file and use it explicitly in the constructor.
Here's one point to add: see if 'in' is null before calling 'in.close()' as the exception could happen without the first assignment succeeding.
Also, it's good form to only catch possible exceptions (e.g. IOException). That way if you add more code and the IDE tells you that a new exception type isn't handled you can add the proper specific code rather than never hearing about it because the catch (Exception ) which was originally for IOException is also (mishandling?) every other type.
Here's the clean Java 7 way which works for anything that implements AutoCloseable/Closeable:
try (InputStream in = compressed ?
new GZIPInputStream(new FileInputStream(inFile))
: new FileInputStream(inFile);
InputStreamReader isr = new InputStreamReader(in))
{
int length = 0;
char[] cbuf = new char[8 * 1024];
while ((length = isr.read(cbuf)) != -1) {
sb.append(cbuf, 0, length);
}
}
catch (Exception e) {
e.printStackTrace();
}
If you're wondering what happens if there's an exception while closing the resource, read about getSuppressedExceptions() which was also added.

Categories