System.out.println() don't throws Exception, but System.in.read() throws Exception, Why?
I got this from Java™ I/O, 2nd Edition By Elliotte Rusty Harold :-
it would be inconvenient to wrap a try/catch block around each call to System.out.println( ), Sun decided to have PrintStream (and later PrintWriter) catch and eat any exceptions thrown inside a print( ) or println( ) method. If you do want to check for exceptions inside a print( ) or println( ) method, you can call checkError( ):
public boolean checkError( )
The checkE开发者_如何转开发rror( ) method returns TRue if an exception has occurred on this print stream, false if one hasn't. It tells you only that an error occurred. It does not tell you what sort of error occurred. If you need to know more about the error, you'll have to use a different output stream or writer class.
I just wana test this checkError method for true return type....
Any clues for creating some practical scenarios for this... :-)
Here's a couple of scenarios where checkError()
will return true
:
Scenario #1
- Open an output stream for a file to a small filesystem/device; e.g. a floppy disc?
- Create a PrintStream
- Loop for ever writing to the PrintStream.
Eventually the filesystem will fill up and writes will fail.
Scenario #2
- Open a URL connection to some HTTP server.
- Get the OutputStream for the connection
- Create a PrintStream
- Write some output to the PrintStream.
- Call getStatus() on the connection, or call
closeConnection
- Try to write some more output.
Writes should now fail because the HTTP connection is no longer in the right state for sending data to the remote server.
These scenarios are practical, in the sense that you should be able to make them give you errors. But they are not entirely realistic. For example, you wouldn't normally use a PrintStream to send POST data to an HTTP server. But that's the root of the differences in the OutputStream versus PrintStream APIs. The OutputStream / Writer APIs are designed for use-cases where the application needs to know if output fails. The PrintStream / PrintWriter APIs are designed for "light-weight" use-cases such as outputting user messages to the console where handling failure is ... umm ... a waste of programmer effort.
精彩评论