简体   繁体   English

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

[英]Exception Handling in Java/checked exceptions

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的新手,并且希望在下面的程序中提供任何受检查的exception帮助,感谢您。

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. Windows上文本文件的理想路径应该是D:\\ file.txt。 But in this program, this syntax gives an error, indicating an incorrect escape syntax(\\n,\\t etc). 但是在此程序中,此语法给出了一个错误,指示错误的转义语法(\\ n,\\ t等)。 Why is the compiler(I'm using Eclipse Kepler on Windows 8.1) treating the path file as an escape seq? 为什么编译器(我在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. 谢谢。

In java (and many other languages), you must escape the back slash with another backslash when coding String literals: 在Java(和许多其他语言)中,在编码字符串文字时,必须用另一个反斜杠转义反斜杠:

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字符串转义序列。

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

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