Java 捕获 IOException
我认为这是基本的东西,但我不知道该怎么做。为什么我会得到 IOException never throw in the body of相应的 try 语句
public static void main(String[] args)
{
File inputFile = null ;
try
{
inputFile = new File("records.txt") ;
}
catch (IOException e)
{
System.out.print("file not found!") ;
}
I think this is basic stuff but i'm not sure what to do. Why do I get IOException never thrown in body of corresponding try statement
public static void main(String[] args)
{
File inputFile = null ;
try
{
inputFile = new File("records.txt") ;
}
catch (IOException e)
{
System.out.print("file not found!") ;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
File 构造函数本身并没有做太多事情。
直到您真正开始执行实际操作时,才能抛出 IOException。
The File constructor in itself doesn't do very much.
It is not until you actually start doing actual operations that IOExceptions can be thrown.
它永远不会抛出 IOException。创建 File 对象不会将其连接到磁盘上的任何内容。也就是没有IO。
如果您尝试从磁盘上没有相应文件的 File 对象读取或写入,您将收到 IOExceptions。例如,如果您尝试从实际上不在磁盘上的文件获取CanonicalPath。
It never throws an IOException. Creating a File object does not connect it to anything on the disk. That is, there is no IO.
If you try to read or write from a File object that does not have a corresponding file on the disk you'll get IOExceptions. Such as if you try to getCanonicalPath from a File that is not actually on the disk.
因为您可以使用任何您想要的字符串实例化文件对象。当您稍后尝试读/写/打开实际文件时,您将收到异常。
Because you can instantiate File object with any string you want. You will get the exception later, when you try to read / write / open the actual file.
< code>File(String) 不会抛出
IOException
,因此此时您无法捕获异常。File(String)
does not throwIOException
, so you can't catch one at that time.如果您想检查文件是否存在,请使用 file.exists() 来执行此操作。除此之外:
永远不要吞下异常 - 始终记录堆栈跟踪或重新抛出异常(例如将其包装在运行时异常中)
不要依赖程序流的异常处理 - 这些应该是例外情况。
If you want to check whether a file exists, do that with
file.exists()
. Apart from that:never swallow exceptions - always log the stacktrace or rethrow the exception (wrapping it in a runtime exception for example)
don't rely on exception handling for the program flow - these should be exceptional cases.