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.
Related
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
Wrote a file in another class and now I'm trying to piece together the file into a JLabel, so I need to convert the name in the file into a string. Using FileReader and a char array to separate each character into an array to be put together in the JLabel.
I'm getting this error on NamePieces[x] = (char)nr;:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
at clients.initialize(clients.java:197)
at clients.<init>(clients.java:72)
This is the code that I want to read the file:
try(FileReader nameReader = new FileReader(NamePath)) {
int nr = nameReader.read();
int x = 0;
while(nr != -1) {
namePieces[x] = (char)nr;
nr = nameReader.read();
x++;
}
}
catch (FileNotFoundException e) {}
catch (IOException e1) {}
String name = String.valueOf(namePieces[0]) + namePieces[1];
Doesn't work
Most likely, your problem occurs because namePieces is not initialized. As was already mentioned in the comments, you should not use char[] as a container for your characters (because in real world you won't know the length of the files' contents every time, so you will probably need to resize your container), it is way more better to use StringBuilder, provided by Java standard library. It will protect you from getting out of bounds.
StringBuilder namePieces = new StringBuilder();
File file = new File(filePath);
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(file),
Charset.forName("UTF-8")));
int c;
while((c = reader.read()) != -1) {
namePieces.append((char) c);
}
String nameString = namePieces.toString(); // Use this string as a complete array of needed characters
As you see I changed an approach by using not only StringBuilder, but also BufferedReader. However, for your task you can leave FileReader as it is. Just consider appending characters to builder.
If your file just contains a String there is a straightforward way to read it:
public String readMyFile( String fileName) throws IOException {
Path path = Paths.get(fileName);
return Files.readAllLines(path).get(0);
}
I'm still very new to java and I'm working on a school assignment that's working on cryptography. When I was searching for methods to read from files I saw many had a try and catch block. I'm not very familiar with the use of these and I want to try and avoid using them in my code but when I remove them I have two exceptions reported at the new in new FileReader and at the bracket after reader.readLine(). But if I do use them it works relatively well. Can anyone explain what is happening? Also when using the catch and try I get an exception Null when my encoding is done. Any help is appreciated.
import java.io.*;
import java.util.*;
public class Encrypter {
public static void main(String[] args) {
File input = null;
if (1 < args.length) {
input = new File(args[1]);
} else {
System.err.println("Invalid arguments count:" + args.length);
System.exit(0);
}
String key = args[0];
BufferedReader reader = null;
try {
int i = 0;
String[] inputText = new String[20];
String[] encryptText = new String[20];
reader = new BufferedReader(new FileReader(input));
while ((inputText[i] = reader.readLine()) != null) {
encryptText[i] = inputText[i];
System.out.println(inputText[i]);
++i;
}
int hash = key.hashCode();
Random random = new Random(hash);
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
String alphabetPerm = alphabet;
char temp;
for (int j = 0; j < 100; j++) {
int n1 = random.nextInt(27) + 0;
int n2 = random.nextInt(27) + 0;
char[] swapper = alphabet.toCharArray();
temp = swapper[n1];
swapper[n1] = swapper[n2];
swapper[n2] = temp;
String alphaSwap = new String(swapper);
alphabet = alphaSwap;
}
System.out.println(alphabet);
for (int k = 0; k < inputText.length; k++) {
encryptText[k] = inputText[k].replaceAll("[^A-Za-z0-9 ]+", " ");
for (int j = 0; j < inputText[k].length(); j++) {
int index = alphabetPerm.indexOf(encryptText[k].charAt(j));
encryptText[k] = alphabetSwapper(encryptText[k], alphabet, index, j);
System.out.println(encryptText[k]);
}
}
} catch (Exception e) {
System.err.println("Caught Exception: " + e.getMessage());
}
}
public static String alphabetSwapper(String s, String alpha, int index, int value) {
char toSwap = s.charAt(value);
char[] inputChars = s.toCharArray();
inputChars[value] = alpha.charAt(index);
String swapped = new String(inputChars);
return swapped;
}
}
You are better off not catching the exception the way you are because you are discarding the two most useful pieces of information, which exception was thrown and where did it happen.
Instead of catching the exception, you can add the exceptions to the throws clause of main()
e.g.
public static void main(String[] args) throws IOException {
// ...
}
Can anyone explain what is happening?
When you read a file you might be an IOException e.g. if the file is not present. You might have to catch this exception but for now you can let the caller to main print it out if it happens.
Also when using the catch and try I get an exception Null when my encoding is done
This means you are triggering an exception without a message. If you print the exception and where it happened(or let the JVM do it for you) you will see where.
To determine why this is happening I suggest stepping through the code in your debugger so you can understand what each line does.
A main method of the form as you pasted is usually the entry point of a program and not called by other java code. So it is good practise to catch and handle all Exceptions before leaving your program.
'Handle' can mean different things:
Simply print the message of the exception to the console as you do (in that case you loose information as Peter Lawrey already pointed out).
Print the stacktrace (e.printStackStrace()) which outputs more information about the exception on the stderr output. This is what java does if the main() method is left with an uncaught exception.
If using a logger framework: Loggers and its Appenders are able to print all exception information into a destination of your choice.
Handle it (1-3) and exit java with an exit code != 0 in order that a (programmatical) caller of your application can handle the error situation.
BTW1: I even would catch Throwable. So you also catch possible unchecked exceptions (NullPointerException, ArrayIndexOutOfBoundsException, etc.). And place the try at the very beginning (if you make an error in accessing your args array you would have covered also the ArrayIndexOutOfBoundsException)
BTW2: If you would not have any try..catch in the main method I assume the code would not even compile because the compiler can detect that there might be unhandled checked exceptions (from your IO operations).
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 :-)
I am trying to write code to import all characters (including spaces) of a given text file into a single string for analysis. I am using the given files in Java for this, and ran across a strange error while putthing it together. I'm not really familiar with coding at all, and would appreciate clarification. What happens is that in the below code, when I set
text.append(ch);
I have errors of Default constructor cannot handle exception thrown by X, must define explicit constructor;
and when I set text.append('ch');
the above errors go away and my 'ch' line just gives invalid char const. error, fixable by removing the ''s.
So I take it I have to construct an explicit constructor for my givens from Java, is this necessary? As I have no idea how to do so, it would be nice to have a roundabout solution.
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.StringBuilder;
public class TextReader //cannot place inputs/outputs of string on this line
{
StringBuilder text = new StringBuilder();
//StringBuilder google
//google end of file check java
InputStream in = new FileInputStream("charfile.txt");
Reader r = new InputStreamReader(in, "US-ASCII");
int intch;
{
while ((intch = r.read()) != -1)
{
char ch = (char) intch;
// ...
text.append(ch); //if I make this a 'ch', the errors above go away, what's the problem?
}
}
}
You need to place your statements in a code block, e.g. main method.
public static void main(String[] args) throws IOException {
StringBuilder text = new StringBuilder();
// StringBuilder google
// google end of file check java
InputStream in = new FileInputStream("charfile.txt");
Reader r = new InputStreamReader(in, "US-ASCII");
int intch;
{
while ((intch = r.read()) != -1) {
char ch = (char) intch;
// ...
text.append(ch);
}
}
}
The statements
InputStream in = new FileInputStream("charfile.txt");
Reader r = new InputStreamReader(in, "US-ASCII");
both throw checked exceptions which cannot occur in the class block.
Actually IO in java require try and catch block, else it will give you error. Also in above code you have to place the declaration in explicitly define constructor
TextReader()
{
//----------- Your Code here.
}
When you do text.append(ch);, error should not come at this line. It may complain about other issue e.g. Expected Exceptions not handled or thrown e.g.
Handled:
try{
while ((intch = r.read()) != -1){
char ch = (char) intch;
// ...
text.append(ch);
}
}catch(IOException ioex){
ioex.printStackTace();
}
Thrown:
Change your method declaration with throws clause as :
public static void main(String[] args) throws IOException{
When you say text.append('ch');, your argument is not a variable or single character literal any more. You should be getting compilation error at that line. Though you can do something like text.append('c'); as c is a single character.