Can I avoid catch block in Java? - 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
}

Related

Try catch, Java eclipse not catching exception

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);
}

java try catch block does not print the information that I want it to

I want the user to enter a filename on the command line. If they don't enter any, I should print information says file was not processed and exit out. Here is my try catch block
try{
parser.openFile(args[0]);
if(parser.getCounter() == 3)
{
System.out.println("File was processed: true");
}
else
{
System.out.println("File was processed: false. Missing information.");
}
//found = true;
}
catch (IOException e)
{
e.printStackTrace();
System.out.println("File was processed: false. Re-enter filename.");
//fName = keyboard.nextLine();
}
The openFile method is in my class, and it is here, in case anyone needs it:
public void openFile (String filename)throws IOException{
fis = new FileInputStream(filename);
br = new BufferedReader(new InputStreamReader(fis));
String thisLine;
thisLine = br.readLine();
while(thisLine != null)
{
lines.add(thisLine);
thisLine = br.readLine();
}
}
Somehow "File was processed: false. Re-enter filename." does not printed out when there is not filename in the command line. Can anyone help me please?
Probably you're getting a different exception. Maybe
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Try to validate the content of args
Example:
public class TesteArgs {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Inform a valid name...");
System.exit(0);
}
// continue handling your args param
System.out.println(args[0]);
}
}
Change your IOException to Exception in your catch statement, that'll get 'em exceptions caught nicely for ya.
You can catch multiple exception in try{}catch{} block.
You have to catch specific exceptions (ArrayIndexOutOfBoundsException, which is child of Exception) first and generic exception (Exception) later.
Sample code:
try{
// Your code
File f = new File ("a.txt");
FileInputStream fio = new FileInputStream(f);
}catch(ArrayIndexOutOfBoundsException ae ){
System.out.println(ae);
}catch(IndexOutOfBoundsException ee ){
System.out.println(ee);
}catch(IOException ioe ){
System.out.println(ioe);
}catch(RuntimeException re ){
System.out.println(re);
}catch(Exception e ){
System.out.println(e);
}catch(Throwable t ){
System.out.println(t);
}
Have a look at hierarchy of exceptions

how can i modify main method to get input and output from the comandline?

Instead of hard coding to read the infile and outfile, I want to read from the command line. How would I do that?
/**
* reads a file and creates a histogram from it
* #param args string of argument
* #precondition none
*/
public static void main(String[] args) {
Histogram hist = new Histogram();
FileInputController input = new FileInputController(hist);
FileOutputController output = new FileOutputController(hist);
try {
input.readWords("infile.txt");
output.writeWords("outfile.txt");
} catch (FileNotFoundException exception) {
System.out.println("exception caught! somthing went wrong: " + exception.getMessage());
} catch (IOException exception) {
System.out.println("exception caught! somthing went wrong: " + exception.getMessage());
} finally {
System.exit(1);
}
}
public static void main(String[] args) {
WordHistogram hist = new WordHistogram();
FileInputController input = new FileInputController(hist);
FileOutputController output = new FileOutputController(hist);
try {
input.readWords(args[0]); //args[0] is the first argument passed while launching Java
output.writeWords(args[1]); //args[1] is the second argument passed while launching Java
} catch (FileNotFoundException exception) {
System.out.println("exception caught! somthing went wrong: " + exception.getMessage());
} catch (IOException exception) {
System.out.println("exception caught! somthing went wrong: " + exception.getMessage());
} finally {
System.exit(1);
}
}
Run your program like: java YourClassName infile.txt outfile.txt
In main(String[] args), args is an array of Strings which contains values of arguments passed while launching Java.
Please DO read Oracle docs about command line arguments for further reading.
to get integer value use like this
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
to get string use this
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
and for output use just System.out.println("your text here");

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>();

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

Categories