Try catch, Java eclipse not catching exception - java

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter file name:");
String name = sc.nextLine();
creatingfeatures(name, "part1");
}
public static void creatingfeatures(String filename, String type) {
String outputFile = "../data/" + type + "/" + type + ".csv";
System.out.println("This is the output file: " + outputFile);
try {
CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true), ',');
for (int i = 0; i < 10 ; i++) {
csvOutput.write(i);
csvOutput.endRecord();
}
csvOutput.close();
}
catch (IOException e) {
System.out.println("Please enter another file name (wrong name given)");
System.exit(0);
}
}
Hello all, when I use an invalid file name (Ie when the file is not found), the message under the catch was not printed. Anybody knows why?

From the documentation it is clear, it does not gives exception for the wrong file name supplied to FileWriter, it rather creates new file if it is not present. Also if it is not able to create a file at a desired location, then it throws IOException. Just check at the location, it should have created files there.
Constructs a FileWriter object given a file name with a boolean
indicating whether or not to append the data written.
Parameters:
fileName String The system-dependent filename.
append boolean if true, then data will be written to the end of the file rather than the beginning. Throws:
IOException if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot
be opened for any other reason

You are catching just IOExceptions
catch (IOException e) {
System.out.println("Please enter another file name (wrong name given)");
System.exit(0);
}
If you have other kind of exceptions you have to catch them also.
Use:
catch (Exception e) {
System.out.println("Other kind of exception");
System.exit(0);
}
instead or in addition to catch any kind of exceptions
catch (IOException e) {
System.out.println("Please enter another file name (wrong name given)");
System.exit(0);
}catch (Exception e) {
System.out.println("Other kind of exception");
System.exit(0);
}

Related

Try/Catch blocks in Java

for the program that I have been assigned, we have to read from a text file, create an ArrayList of objects called NameInformation that contains the information from the file, and then prompt the user for a name and gender (Gender is one of the variables in the NameInformation class) and the computer will tell how many boys or girls had the given name.
Can files be accessed and used outside of a try catch block? I want to try something like this:
try {
FileReader inFile = new FileReader (FILE_NAME);
} catch (FileNotFoundException e) {
System.out.println ("The file " + FILE_NAME + " does not exist");
System.exit(-1);
}
Scanner file = new Scanner (infile);
ArrayList<NameInformation> nameList = new ArrayList<NameInformation>();
I tried the above code and kept getting an error message. The only way I could get it to work somewhat was to make the try block massive. Is that the only way to do it? I feel like having a massive try block is incorrect.
I want to add elements to the ArrayList too, but can't seem to get it right.
while (file.hasNextLine()) {
NameInformation babyName = new NameInformation(file.nextLine());
nameList.add(babyName);
}
But this doesn't quite do what I want it to.
You can do it like this and give only error throwing code into try catch block, you are never passing catch block anyway because system exits there, otherwise you should check that file isn't null afterwards:
FileReader inFile = null;
try {
inFile = new FileReader (FILE_NAME);
} catch (FileNotFoundException e) {
System.out.println ("The file " + FILE_NAME + " does not exist");
System.exit(-1);
}
Scanner file = new Scanner (infile);
ArrayList<NameInformation> nameList = new ArrayList<NameInformation>();
Initializing the file should be in Try Catch Block. But you should declare it outside the block to access it outside. Example:
FileReader inFile = null;
try {
inFile = new FileReader (FILE_NAME);
} catch (FileNotFoundException e) {
System.out.println ("The file " + FILE_NAME + " does not exist");
System.exit(-1);
}
Scanner file = new Scanner (infile);
ArrayList<NameInformation> nameList = new ArrayList<NameInformation>();

Why is my text file not overwriting after each execution?

My program reads in a text file, in.txt. That text file can have an arbitrary amount of lines.
My problem is that when I try to write to the output (out.txt) file, it appends it instead of overwriting.
The output file should have the same number as the input file.
try {
inFile = new Scanner(new File("in.txt"));
while (inFile.hasNext()) {
// Methods and stuff that doesn't matter...
// Problem starts here
try{
outFile = new PrintWriter((new FileWriter("out.txt", true)));
outFile.println(ArrayToString(intArray));
}
catch (IOException e) {
System.out.print("Could not find and write to the output file. " + e);
e.printStackTrace();
}
finally {
outFile.flush();
outFile.close();
}
}
}
catch (FileNotFoundException e) {
System.out.print("Could not find the input file. " + e);
e.printStackTrace();
}
The ArrayToString method returns a string to write.
EDIT:
I forgot to add this detail:
After reading the instructions again, I am not supposed to be creating a text file, just checking if it's there.
See the Javadoc for the FileWriter constructor:
public FileWriter(String fileName,
boolean append)
throws IOException
Constructs a FileWriter object given a file name with a boolean
indicating whether or not to append the data written.
Try setting the append flag to false. Then use the same writer instead of creating a new one each time through the loop (meaning that you should declare the FileWriter above the start of your while loop).
(Btw check out java.util.Arrays.toString, you shouldn't need to write your own code for this.)
The problem is here:
try{
outFile = new PrintWriter((new FileWriter("out.txt", true)));
outFile.println(ArrayToString(intArray));
}
catch (IOException e) {
System.out.print("Could not find and write to the output file. " + e);
e.printStackTrace();
}
Change the PrintWriter line to:
outFile = new PrintWriter((new FileWriter("out.txt", false)));
Now, it looks like you're opening the file on every loop through your input file. If you are wanting to open this file once, and write to it for each line in the input file, move the open and close outside the while loop like this:
try {
inFile = new Scanner(new File("in.txt"));
// here we open the out file, once
outFile = new PrintWriter((new FileWriter("out.txt", false)));
while (inFile.hasNext()) {
// Methods and stuff that doesn't matter...
// Problem starts here
try{
// this will write a line to the out.txt file containing the intArray as a String
outFile.println(ArrayToString(intArray));
}
catch (IOException e) {
System.out.print("Could not find and write to the output file. " + e);
e.printStackTrace();
}
}
}
catch (FileNotFoundException e) {
System.out.print("Could not find the input file. " + e);
e.printStackTrace();
}
finally {
inFile.close();
outFile.flush();
outFile.close();
}
change
outFile = new PrintWriter((new FileWriter("out.txt", true)));
to
outFile = new PrintWriter((new FileWriter("out.txt", false)));
and
outFile.println(ArrayToString(intArray));
to
outFile.print(ArrayToString(intArray));

FileNotFoundException catch error when reading from file in Java

I am trying to write a simple program that reads integers in from a text file and then outputs the sum to an output file. The only error I am getting is in my catch block at line 38 "Unresolved compilation problem: file cannot be resolved". Note that "file" is the name of my input file object. If I comment out this exception block, the program runs fine. Any advice would be appreciated!
import java.io.*;
import java.util.Scanner;
public class ReadWriteTextFileExample
{
public static void main(String[] args)
{
int num, sum = 0;
try
{
//Create a File object from input1.txt
File file = new File("input1.txt");
Scanner input = new Scanner(file);
while(input.hasNext())
{
//read one integer from input1.txt
num = input.nextInt();
sum += num;
}
input.close();
//create a text file object which you will write the output to
File output1 = new File("output1.txt");
//check whether the file's name already exists in the current directory
if(output1.exists())
{
System.out.println("File already exists");
System.exit(0);
}
PrintWriter pw = new PrintWriter(output1);
pw.println("The sum is " + sum);
pw.close();
}
catch(FileNotFoundException exception)
{
System.out.println("The file " + file.getPath() + " was not found.");
}
catch(IOException exception)
{
System.out.println(exception);
}
}//end main method
}//end ReadWriteTextFileExample
The file variable is declared within the try block. It's out of scope in the catch block. (Although it couldn't happen in this case, imagine if the exception were thrown before execution had even reached the variable declaration. Basically, you can't access a variable in a catch block which is declared in the corresponding try block.)
You should declare it before the try block instead:
File file = new File("input1.txt");
try
{
...
}
catch(FileNotFoundException exception)
{
System.out.println("The file " + file.getPath() + " was not found.");
}
catch(IOException exception)
{
System.out.println(exception);
}
Scope in Java is based on blocks. Any variable you declare inside a block is only in scope until the end of that same block.
try
{ // start try block
File file = ...;
} // end try block
catch (...)
{ // start catch block
// file is out of scope!
} // end catch block
However, if you declare file before your try block, it will remain in scope:
File file = ...;
try
{ // start try block
} // end try block
catch (...)
{ // start catch block
// file is in scope!
} // end catch block

Can I avoid catch block in Java?

Inside a method, I use a Scanner to read text inside a file. This file doesn't always exist, and if it doesn't, I want simply to do nothing (i.e. no scan).
Of course I could use a try/catch like this:
String data = null;
try
{
Scanner scan = new Scanner(new File(folder + "file.txt"));
data=scan.nextLine();
scan.close();
}
catch (FileNotFoundException ex)
{
}
My question is what can I do to avoid the try/catch? Because I don't like local variable unused. I was thinking of something like:
String data = null;
File file_txt = new File(folder + "file.txt");
if (file_txt.exists())
{
Scanner scan = new Scanner(file_txt);
data=scan.nextLine();
scan.close();
}
But of course with this I get an error in Netbeans and I can't build my project...
No, It's checked exception. try must be followed with either catch block and/or finally block. There are two method for handling checked exception.
Method 1 : Either wrap your code using try/catch/finally
Option 1
try{
Scanner scan = new Scanner(new File(folder + "file.txt"));
data=scan.nextLine();
scan.close();
}
catch (FileNotFoundException ex)
{
System.out.println("Caught " + ex);
}
Option 2
try{
Scanner scan = new Scanner(new File(folder + "file.txt"));
data=scan.nextLine();
scan.close();
}
finally
{
System.out.println("Finally ");
}
Option 3
try{
Scanner scan = new Scanner(new File(folder + "file.txt"));
data=scan.nextLine();
scan.close();
}catch(FileNotFoundException ex){
System.out.println("Caught " + ex );
}finally{
System.out.println("Finally ");
}
Method 2: Throw exception using throw and list all the exception with throws clause.
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Note : Checked Exception means Compiler force you to write something to handle this error/exception. So, AFAIK, there is no any alternative for checked exception handling except above method.
FileNotFoundException is checked exception, Due to catch or specify behavior, you need to either catch (or) specify it in throws clause of method declaration.
how about
catch (FileNotFoundException ex)
{
// create a log entry about ex
}

throw nex exception returning to reading

I have to read a text and I created a method
public void load(String fname){
try{
BufferedReader reader = new BufferedReader(new FileReader(fname));
String id_cliente = reader.readLine();
while(id_cliente!=null){
String name_surname = reader.readLine();
int num_titoli = Integer.parseInt(reader.readLine());
String[] sb = name_surname.split(" ");
Cliente cl = new Cliente(id_cliente,sb[0],sb[1]);
clientilist.put(Integer.parseInt(id_cliente.substring(1)),cl);
for(int i = 0; i < num_titoli; i++){
cl.addTitolo(String titolo = reader.readLine());
}
id_cliente = reader.readLine();
}
}
catch(FileNotFoundException fnfe){
try{
}
catch(FileNotFoundExeption fnfe){
System.exit(0);
}
}
catch(IOException ioe){
}
}
what I would do is to check if the fname file exists.if it's not a FileNotFoundExceptionwill be thrown.Inside it I have to try to open another file.if it is not present so exit with an error message.how can i do?
In the catch block of the first try catch statement you could put any code you want and it will be executed when the exception occurs. You could read another file, try reading the same file again, ask user to point to the correct file, ...
But as mentioned a better solution is to check if the file exists before you create the reader. And if that fails you can fallback on another file (what if that one fails also?)
In the next code I adapted your method to have a check and throw an exception if file isn't valid. On using that method you can react on that. Note that you haven't opened any readers if you gave 2 invalid filenames.
try{
load(fname);
}catch(Exception e){
try{
load(alternativeFName);
}catch(Exception e){
System.out.println("None of the files are available");
e.printStackTrace();
}
}
And this is how your load function would look like:
public void load(String fname) throws Exception {
// try opening file
File file = new File(fname);
// check if valid file
if( !file.exists() ){
// if no valid file throw exception so we can react on that
throw new Exception("File not available: "+fname);
}
//your code for reading here, at this point you know the file exists
//...
}
It´d be simpler to check first if the file exist, instead of waiting for the exception:
File f = new File(fname);
if (!f.exists()) {
// similarly, check for the existence of the other file, exit if necessary
}

Categories