Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have you ever seen a Java File close() throw an exception?

Tags:

Has anyone ever seen an exception thrown when calling close method on any closable object?

like image 766
The Student Avatar asked May 04 '10 13:05

The Student


People also ask

Can you throw exception in Java?

Any code can throw an exception: your code, code from a package written by someone else such as the packages that come with the Java platform, or the Java runtime environment. Regardless of what throws the exception, it's always thrown with the throw statement.

What does it mean to throw an exception Java?

The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

What happens if you don't close a file in Java?

If you write to a file without closing, the data won't make it to the target file. But after some surfing I got to know that Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.

How do you close a file in Java?

Use the close() Method to Close a File in Java.


1 Answers

An IOException will be thrown on close if the final flush fails. Possible causes include:

  • the file system is full, or the user is over quota,
  • hard disc errors,
  • a file system was forcibly unmounted,
  • a remote file system is unavailable due to networking or other problems,
  • (possibly) a character encoding error if writing to the file via an OutputStreamWriter or similar,
  • a device error if the "file" is a device file,
  • a lost connection if the closeable is a network stream,
  • a broken pipe if the closeable is a pipe to external process,
  • and so on.

I have certainly seen some of these. Others are unlikely.

However, if the data you are writing is important then you should allow for close failing. For example, if your application is writing out a critical file the file system fills up, your application had better notice this before it replaces the old copy of the file with the truncated version.

like image 95
Stephen C Avatar answered Dec 19 '22 23:12

Stephen C