我可以避免Java中的catch块吗?
在一种方法中,我使用扫描仪读取文件中的文本。该文件并不总是存在,如果不存在,我只是想什么也不做(即不扫描)。
当然,我可以这样使用try / catch:
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();
}
但是,与此同时,我在Netbeans中遇到了一个错误,但我无法建立我的项目...
But of course with this I get an error in Netbeans and I can't build my project...
否,已检查异常。 try 之后必须是 catch 块和/或最终块。有两种方法可以处理受检查的异常。
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.
方法1:可以使用 try / catch / finally $ c包装代码$ c>
Method 1 : Either wrap your code using try/catch/finally
选项1
try{
Scanner scan = new Scanner(new File(folder + "file.txt"));
data=scan.nextLine();
scan.close();
}
catch (FileNotFoundException ex)
{
System.out.println("Caught " + ex);
}
选项2
try{
Scanner scan = new Scanner(new File(folder + "file.txt"));
data=scan.nextLine();
scan.close();
}
finally
{
System.out.println("Finally ");
}
选项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 ");
}
方法2:使用 throw抛出异常
并列出所有带有 throws
子句的异常。
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);
}
}
}
注意:已检查的异常表示编译器会强制您编写一些内容来处理此错误/异常。因此,AFAIK除了上述方法外,没有其他方法可以用于检查异常。
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.