Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an alternative to try/catch in Java for opening a file?

I remember in my c++ class we would use the following code to handle bugs when opening a file:

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

Now that I'm learning java, I'm having trouble using try/catch statements, because when I create a scanner to read my input file, it isn't recognized outside of that try code block. Is there any equivalent to fail() and exit(0) in java, or is there a better method?

like image 332
Brent Allard Avatar asked Dec 28 '25 10:12

Brent Allard


2 Answers

I'm having trouble using try/catch statements, because when I create a scanner to read my input file, it isn't recognized outside of that 'try' code block.

Good! You shouldn't be using it outside your try block. All of the relevant processing of the file should be inside the try block, e.g.:

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

(That's using the newish try-with-resources.)

In the above, I'm assuming when you said Scanner, you were specifically talking about the Scanner class.

Answering your actual question: No, that's just not the standard practice in Java code. Java embraces exceptions.

like image 183
T.J. Crowder Avatar answered Dec 31 '25 00:12

T.J. Crowder


To have the Scanner be visible outside of the try...catch block, just declare the variable outside of the block:

Scanner scanner = null;

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

Now you can use your scanner object outside of the try...catch block. To check if the initialization was successful you can check against null if you really have to, but usually error handling should be done inside the catch block, eg

try {
    scanner = ... //Initialize scanner
} catch (IOException e) {
    System.out.println("Failure. Exiting");
    exit(1);
}
like image 44
Marv Avatar answered Dec 30 '25 22:12

Marv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!