Is there a try / catch alternative in Java to open a file?

I remember that in my class, c++

we used the following code to handle errors when opening a file:

ifstream in;
in.open("foo.txt");
if(in.fail()){
   cout << "FAILURE. EXITING..." << endl;
   exit(0);
}

      

Now as I study java

, I am having problems using operators try/catch

because when I create a scanner to read my input file, it is not recognized outside of that block of code try

. Is there an equivalent to fail()

and exit(0)

in java

, or is there a better method?

+3


source to share


3 answers


I am having problems using try / catch statements because when I create a scanner to read my input file it is not recognized outside of this try code.

Good! You shouldn't use it outside of your block try

. All relevant file processing should be inside the block try

, for example:

try (
    InputStream istream = new FileInputStream(/*...*/); // Or Reader or something
    Scanner scanner = new Scanner(istream)
    ) {
    // Use `scanner` here
}
// Don't use `scanner` here

      



(This is using new tries with resources.)

In the above, I am assuming that when you said Scanner, you were talking specifically about a class Scanner

.

To answer your real question: No, this is not standard practice for Java code. Java covers exceptions.

+3


source


To Scanner

display outside the block try...catch

, simply declare the variable outside the block:

Scanner scanner = null;

try {
    scanner = ... //Initialize scanner
} catch (IOException e) {
    //Catch
}

      



You can now use your scanner object outside the block try...catch

. To test if the initialization was successful, you can check null

if you really need to, but usually error handling should be done inside a block catch

, for example

try {
    scanner = ... //Initialize scanner
} catch (IOException e) {
    System.out.println("Failure. Exiting");
    exit(1);
}

      

+1


source


You can add Exception throws to the method in which you are using the scanner.

void method_name () throws Exception {method definition}

This way, the method knows that some part of the code will throw an exception and must be handled.

0


source







All Articles