开发者

System.out.println() don't throws Exception, but System.in.read() throws Exception, Why?

开发者 https://www.devze.com 2022-12-09 09:34 出处:网络
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 (a

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

  1. Open an output stream for a file to a small filesystem/device; e.g. a floppy disc?
  2. Create a PrintStream
  3. Loop for ever writing to the PrintStream.

Eventually the filesystem will fill up and writes will fail.

Scenario #2

  1. Open a URL connection to some HTTP server.
  2. Get the OutputStream for the connection
  3. Create a PrintStream
  4. Write some output to the PrintStream.
  5. Call getStatus() on the connection, or call closeConnection
  6. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消