Would this be problematic and run into issues?
Example:
try {
File Reader fileReader = new FileReader(blah);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// while-statement -- extract information from blah
try {
File Reader fileReader2 = new FileReader(blah2);
BufferedReader bufferedReader2 = new BufferedReader(fileReader2);
// while-statement -- extract information from blah2
} catch (FileNotFoundException ex) {
// Display FileNotFound stuff
} catch (IOException ex) {
// Display IOException stuff
}
} catch (FileNotFoundExcpetion ex) {
// Display FileNotFound stuff
} catch (IOException ex) {
// Display IOException stuff
}
}
If it is problematic, what other approach should I look to?
Too many try-catch would complicate code and reduce the code readability which will lead to swallowing an exception and its much more worse than performance issues as it can crash your system unexpectedly.
Here is an example of swallowing an exception and its side effects (multiple point of failures like NPE etc.).
public static void main(String[] args) {
String dataFromFile = null, dataFromDataBase = null;
try {
try {
dataFromFile = readFile();
} catch (IOException e) {
// ignore exception
// String dataFromFile will be set to null
// as there was an exception
}
// imagine many lines of code here
dataFromDataBase = readDatabase(dataFromFile.getKey());
} catch (IOException e) {
// ignore exception
}
// imagine many lines of code here
System.out.println(dataFromFile.replace(" ", ""));
//imagine many lines of code here
System.out.println(dataFromDataBase.getKey());
}
private static String readFile() throws IOException {
// throws ioexception
}
private static String readDatabase(String key) throws IOException {
// throws ioexception
}
If you are expecting multiple points in a single method that can throw exceptions then club them into one try-catch and handle them appropriately. Again there can be exception to this specific question but you should always try to reduce multiple try-catch in single method.
Unless you are doing something specific with an exception, use single Exception clause to handle all exception and log details or throw it to the caller to handle it in its own specific ways.
try {
File Reader fileReader = new FileReader(blah);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// while-statement -- extract information from blah
File Reader fileReader2 = new FileReader(blah2);
BufferedReader bufferedReader2 = new BufferedReader(fileReader2);
// while-statement -- extract information from blah2
} catch (Exception ex) {
// Display Exception stuff details
}
}
In this example I see no reason to start a new try statement. why not do this?
try {
File Reader fileReader = new FileReader(blah);
BufferedReader bufferedReader = new BufferedReader(fileReader);
File Reader fileReader2 = new FileReader(blah2);
BufferedReader bufferedReader2 = new BufferedReader(fileReader2);
} catch (FileNotFoundExcpetion ex) {
// Display FileNotFound stuff
} catch (IOException ex) {
// Display IOException stuff
}
But no, there would be no problem. it just looks bad. but sometimes needed I guess.
Related
So I have a working ObjectOutputStream in a method that I start by calling the method in main. I need to then read the file it created and print out all 5 objects in it. Right now I'm only printing out the first object.
public static AccountSerializable serializReadObject() throws ClassNotFoundException, IOException {
AccountSerializable read = null;
try { // Create an input stream for file accounts.ser
ObjectInputStream input = new ObjectInputStream(new FileInputStream("accounts.ser"));
read = (AccountSerializable) input.readObject();
input.close();
} catch (IOException i) {
throw i;
}catch(ClassNotFoundException c){
throw c;
}
return read;
}
public static void main(String[] args) {
try {
System.out.println(serializReadObject());
} catch (ClassNotFoundException | IOException e) {
System.out.println("Class not found");
e.printStackTrace();
}
}
I've tried to throw
boolean eof = false;
while(!eof){
try{
//read data
}catch(EOFException e){
eof = true;
}
}
in serializReadObject To loop it and I've also tried to instead catch it in main but I keep getting an error stating "Unreachable catch block for EOFException it is already handled by the catch block"
I then tried to take away the IOException and just put EOFEception but alas it keeps forcing me to surround my read with IOException. Is there another way to loop this with EOF?
You're only getting the first object because your opening and closing the stream on each call. There are many ways to achieve what you want. One way is to use a List<AccountSerializable>:
public static List<AccountSerializable> serializeReadObjects() throws IOException, ClassNotFoundException {
// create an input stream for file accounts.ser
// this line will throw an IOException if something goes wrong
// we don't need to catch it in this method though
ObjectInputStream input = new ObjectInputStream(new FileInputStream("accounts.ser"));
// create list to hold read in accounts
List<AccountSerializable> accounts = new ArrayList<>();
// keep reading until EOFException is thrown
boolean keepReading = true;
while(keepReading) {
try {
// read in serialized account
AccountSerializable read = (AccountSerializable) input.readObject();
// add read in serialized account to the list
accounts.add(read);
} catch(EOFException eofe) {
// we are at the end of file, so stop reading
keepReading = false;
input.close();
} catch(IOException ioe) {
// input stream error other than EOF, not sure what to do
input.close();
throw ioe;
} catch(ClassNotFoundException cnfe) {
// not sure what to do in this case, so close input
input.close();
throw cnfe;
}
}
return accounts;
}
public static void main(String[] args) {
List<AccountSerializable> accounts = null;
try {
// get list of read in accounts
accounts = serializeReadObjects();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
// iterate over list of read in accounts and output them to stdout
for(AccountSerializable account : accounts) {
System.out.println(account);
}
}
public class deleteFile {
public static void main(String args[]){
StringBuffer fileNameStr = new StringBuffer();
fileNameStr.append("c:/");
fileNameStr.append("Test");
File file = new File(fileNameStr.toString());
String systemDateTime = null;
try {
systemDateTime = con.getSystemDateTime();
} catch (SQLException e) {
file.delete();
}
}
}
According to this code, when I get SQLException, it can't delete file. Why?
There is nothing special about deleting a file in a catch block.
If your code (above) is not deleting the file, then it could be a number of things:
You may have the file pathname incorrect.
The file may not exist in the first place.
Your application may not have permission to delete the file, due to normal file / directory permission issues, "mandatory access control" restrictions (e.g. SELinux) or Java sandbox restrictions.
The file may be undeletable because it is "in use" ... on Windows.
That particular exception may not be being thrown.
Your catch block with SqlException never catching.
Use finally{} block in order to delete file or free resource.
Actually my full source code is,
public class deleteFile {
public static void main(String args[]){
-------------------------
StringBuffer fileNameStr = new StringBuffer();
fileNameStr.append(.....);
fileNameStr.append(.....);
File file = new File(fileNameStr.toString());
PrintWriter printWriter = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file),
"windows-31j")));
String systemDateTime = null;
try {
systemDateTime = con.getSystemDateTime();
} catch (SQLException e) {
file.delete();
}
}
Finally I found the solution that is need to close printWriter before deletion file. Thank you for your advice.
try {
systemDateTime = con.getSystemDateTime();
} catch (SQLException e) {
printWriter.flush();
printWriter.close();
file.delete();}
}
Could you help me understand where should I throw exceptions and catch them.
Please, have a look at my code. I thought that in Thrd class I have already thrown and caught the exception. But when I wrote in the main class FirstThread.readFile("ParallelProgramming.txt");, I faced a runtime error - unhandled exception. So, I had to use try and catch. So, I somehow can't understand why in the Thd class my try and catch blocks didn't work.
package parallelprogramming;
import java.lang.Thread;
import java.io.*;
public class Thrd extends Thread {
public void readFile(String File) throws FileNotFoundException {
FileReader fr = new FileReader(File);
BufferedReader br = new BufferedReader(fr);
String s;
try {
while ((s = br.readLine()) != null) {
System.out.println(s);
}
fr.close();
}
catch (FileNotFoundException FNFD) {
System.out.println("File not found!");
}
catch (IOException IOE){
System.out.println("IOException caught!");
}
}
}
package parallelprogramming;
import java.io.FileNotFoundException;
public class ParallelProgramming {
public static void main(String[] args) throws FileNotFoundException {
Thrd FirstThread = new Thrd();
try {
FirstThread.readFile("ParallelProgramming.txt");
} catch (FileNotFoundException FNFD) {
System.out.println("File not found!");
}
}
}
The rules with checked exceptions (and this includes IOException, which FileNotFoundException is a child of), are as follows:
if you cannot, or do not want, to handle it in your current method, declare that the method throws it;
if you want to handle it in your current method, then catch it; note that even in this case you can rethrow that exception;
if main() throws any exception, and this exception triggers, the program terminates.
Now, we suppose that you are using Java 7. In this case, do that:
public void readFile(final String file)
throws IOException
{
final Path path = Paths.get(file);
for (final String line: Files.readAllLines(path, StandardCharsets.UTF_8))
System.out.println(line);
}
Why bother? ;)
If you don't want to do that but read line by line, then:
public void readFile(final String file)
throws IOException
{
final Path path = Paths.get(file);
try (
final BufferedReader reader = Files.newBufferedReader(path,
StandardCharsets.UTF_8);
) {
String line;
while ((line = reader.readLine()) != null)
System.out.println(line);
}
}
The second form is preferred if you wish to treat exceptions specifically. Note that with Java 7, you have meaningful exceptions as to why you cannot access the file vs IOException: NoSuchFileException, AccessDeniedException, etc etc. All these inherit FileSystemException. The old file API can't do that for you.
This means that if you want to deal with filesystem level errors you can do:
catch (FileSystemException e) { /* ... */ }
where before that you did:
catch (FileNotFoundException e) { /* ... */ }
Translated to the code above, if you want to catch exceptions you'll then do:
// All exceptions handled within the method -- except if you rethrow it
public void readFile(final String file)
{
final Path path = Paths.get(file);
try (
final BufferedReader reader = Files.newBufferedReader(path,
StandardCharsets.UTF_8);
) {
String line;
while ((line = reader.readLine()) != null)
System.out.println(line);
} catch (FileSystemException e) {
// deal with a filesystem-level error
// Note that you MUSt catch it before IOException
// since FileSystemException inherits IOException
} catch (IOException e) {
// deal with a low-level I/O error
}
}
Remove 'throws FileNotFoundException' from the readFile method of class Thrd then you dont need to handle this exception in main method of class ParallelProgramming.
As you throw FileNotFoundException from readFile method then exception will pass to the method will called this i.e. then main method need to handle this exception.
There are two ways to handle an exception either you need to catch it or throw it again.
In the readFile method you have done both. you caught the exceptions using catch blocks then you have mentioned that readFile method throws FileNotFoundException, so when ever you use readFile method you need to catch the exception again.
I've not been able to resolve the following exception in the code below. What is the problem with the way I use BufferedReader? I'm using BufferedReader inside the main method
OUTPUT :-
ParseFileName.java:56: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
// ParseFileName is used to get the file name from a file path
// For eg: get - crc.v from "$ROOT/rtl/..path/crc.v"
import java.util.regex.Pattern;
import java.io.*;
public class ParseFileName {
//Split along /'s , and collect the last term.
public String getName (String longName) {
String splitAt = "/";
Pattern pattern1 = Pattern.compile(splitAt);
String[] parts = pattern1.split(longName);
System.out.println("\nparts.length = " + parts.length);
//Return the last element in the array of strings
return parts[parts.length -1];
}
public static void main(String[] args) {
ParseFileName superParse = new ParseFileName();
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
String line;
while ((line = buffread.readLine())!= null) {
String fileName = superParse.getName(line);
System.out.println("\n" + line + " => " + fileName);
}
buffread.close();
}
}
UPDATE :
The following works:
public static void main(String[] args) throws FileNotFoundException, IOException {
However try.. catch still has some nagging issues for me:
try {
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex2) {
ex2.printStackTrace();
}
buffread dosent seem to get the file name. I get this error:
javac ParseFileName.java ParseFileName.java:67: cannot resolve symbol
symbol : variable buffread
location: class ParseFileName
while ((line = buffread.readLine())!= null) {
Add throws FileNotFoundException, IOException in the header of your method. It looks like just throwing the IOException will solve your problem, but incorporating both will allow you to tell if there was a problem with the file's existence or if something else went wrong (see catch statements below).
i.e.
public static void main(String[] args) throws FileNotFoundException, IOException {
Alternately, if you'd like to catch a specific exception and do something with it:
try {
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
// Do something with 'ex'
} catch (IOException ex2) {
// Do something with 'ex2'
}
Update to resolve the updated issue: This is just a simple scope problem which can be solved by declaring the BufferedReader outside of the try statement.
BufferedReader buffread = null;
try {
buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
...
You have to add throws statement into the signature of method main or wrap code in
try {
...
} catch (FileNotFoundException e) {
...
}
Your code can throw FileNotFoundException or IOException which is Checked Exception. You need to surround your code in a try-catch block or add a throws declaration in your main function.
The BufferReader can throw an exception if the file cannot be found or opened correctly.
This error message is telling you that you need to handle this exception. You can wrap the line where you create the BufferReader in a try/catch block. This will handle the case an IOException is thrown and print out the stack trace.
public static void main(String[] args) {
ParseFileName superParse = new ParseFileName();
BufferedReader buffread;
try
{
buffread= new BufferedReader (new FileReader("file.txt"));
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
String line;
while ((line = buffread.readLine())!= null) {
String fileName = superParse.getName(line);
System.out.println("\n" + line + " => " + fileName);
}
buffread.close();
}
Another option is to add "throws IOException" to your method header.
public static void main(String[] args) throws IOException {
//...
}
This tells the compiler and callers of your method that you are choosing to not handle this exception and there is a chance it will be thrown.
public void tokenize(){
// attempt creating a reader for the input
reader = this.newReader();
while((line = reader.readLine())!=null){
tokenizer = new StringTokenizer(line);
while(tokenizer.hasMoreTokens()){
toke = (tokenizer.nextToken().trim());
this.tokenType(toke);
//System.out.println(this.tokenType(toke));
}
}
}
private BufferedReader newReader(){
try {//attempt to read the file
reader = new BufferedReader(new FileReader("Input.txt"));
}
catch(FileNotFoundException e){
System.out.println("File not found");
}
catch(IOException e){
System.out.println("I/O Exception");
}
return reader;
}
I thought I had handled it within newReader() but it appears to be unreachable. Eclipse recommends a throws but I don't understand what that's doing, or if it's even solving the problem?
Appreciate the help!
If you don't know how to handle an IOException in this method, then it means that it's not the responsibility of the method to handle it, and it should thus be thrown by the method.
The reader should be closed in this method, though, since this method opens it:
public void tokenize() throws IOException {
BufferedReader reader = null;
try {
// attempt creating a reader for the input
reader = this.newReader();
...
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException e) {
// nothing to do anymore: ignoring
}
}
}
}
Also, note that unless your class is itself a kind of Reader wrapping another reader, and thus has a close method, the reader shouldn't be an instance field. It should be a local variable as shown in my example.