Java /已检查异常中的异常处理

时间:2021-12-03 20:18:43

I am new to Java, and would appreciate any help in the following program, where I am trying to provide for a checked exception.

我是Java新手,非常感谢以下程序中的任何帮助,我试图提供检查异常。

Her's example:

package book1;
import java.io.*;

public class CheckedException {

public static void main(String[] args) {
openFile("D:Java.txt");

} 

public static void openFile(String name)
{
try
{
FileInputStream f=new FileInputStream(name );
}
catch(FileNotFoundException e)
{
System.out.println("File Not Found!!");
}
}
}

The problem:

  1. The ideal path to a text file on Windows should be D:\file.txt. But in this program, this syntax gives an error, indicating an incorrect escape syntax(\n,\t etc). Why is the compiler(I'm using Eclipse Kepler on Windows 8.1) treating the path file as an escape seq?

    Windows上文本文件的理想路径应为D:\ file.txt。但在此程序中,此语法会出错,表示错误的转义语法(\ n,\ t等)。为什么编译器(我在Windows 8.1上使用Eclipse Kepler)将路径文件视为转义序列?

  2. Even when I removed the \ from the notation(path D:java.txt), the program throws the file not found exception, and is subsequently caught which displays the file not found message.

    即使我从符号(路径D:java.txt)中删除了\,程序也会抛出找不到文件的异常,然后被捕获,显示文件未找到消息。

Please help,

thank you.

1 个解决方案

#1


4  

In java (and many other languages), you must escape the back slash with another backslash when coding String literals:

在java(以及许多其他语言)中,在编写String文字时,必须使用另一个反斜杠转义反斜杠:

openFile("D:\\Java.txt"); // This is the string D:\Java.txt

but java understands forward slashes in file paths on operating systems that use backslashes for separators, so you could just do this:

但java理解在使用反斜杠分隔符的操作系统上的文件路径中的正斜杠,所以你可以这样做:

openFile("D:/Java.txt");

To explain the error you're seeing, the string literal "\:" is an "escaped colon", which is not a valid java string escape sequence.

为了解释您所看到的错误,字符串文字“\:”是一个“转义冒号”,它不是有效的java字符串转义序列。

#1


4  

In java (and many other languages), you must escape the back slash with another backslash when coding String literals:

在java(以及许多其他语言)中,在编写String文字时,必须使用另一个反斜杠转义反斜杠:

openFile("D:\\Java.txt"); // This is the string D:\Java.txt

but java understands forward slashes in file paths on operating systems that use backslashes for separators, so you could just do this:

但java理解在使用反斜杠分隔符的操作系统上的文件路径中的正斜杠,所以你可以这样做:

openFile("D:/Java.txt");

To explain the error you're seeing, the string literal "\:" is an "escaped colon", which is not a valid java string escape sequence.

为了解释您所看到的错误,字符串文字“\:”是一个“转义冒号”,它不是有效的java字符串转义序列。