简体   繁体   English

在Java中使用try / catch打开文件有替代方法吗?

[英]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: 我记得在我的c++类中,我们将在打开文件时使用以下代码来处理错误:

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. 现在我正在学习java ,我在使用try/catch语句时遇到了麻烦,因为当我创建一个扫描程序来读取我的输入文件时,它在该try代码块之外无法识别。 Is there any equivalent to fail() and exit(0) in java , or is there a better method? java是否有任何等效的fail()exit(0) ,还是有更好的方法?

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. 我在使用try / catch语句时遇到了麻烦,因为当我创建一个扫描程序来读取我的输入文件时,它不能在'try'代码块之外识别。

Good! 好! You shouldn't be using it outside your try block. 你不应该在try块之外使用它。 All of the relevant processing of the file should be inside the try block, eg: 文件的所有相关处理都应该 try块内,例如:

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. 在上面,我假设当你说Scanner时,你是专门谈论Scanner类的。

Answering your actual question: No, that's just not the standard practice in Java code. 回答你的实际问题:不,这不是Java代码中的标准做法。 Java embraces exceptions. Java包含异常。

To have the Scanner be visible outside of the try...catch block, just declare the variable outside of the block: 要使Scannertry...catch块之外可见,只需在块之外声明变量:

Scanner scanner = null;

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

Now you can use your scanner object outside of the try...catch block. 现在,您可以在try...catch块之外使用您的scanner对象。 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 要检查初始化是否成功,如果确实需要,可以检查null ,但通常应在catch块内部进行错误处理,例如

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

You can add throws Exception to the method in which you are using scanner. 您可以向使用扫描程序的方法添加throws Exception。

void method_name() throws Exception{definition of method} void method_name()throws Exception {method of method}

By this, method knows about some part of code will throw exception and needed to be handled. 通过这种方法,方法知道代码的某些部分将抛出异常并需要处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM