Error Handling

You may have noticed something a little funny with the code fragments in this chapter: I haven't put any try-catch blocks around them. That's not an oversight. PrintStream methods never throw IOExceptions. Each method in the class catches IOException. When an exception occurs, an internal flag is set to TRue. You can test this flag using the checkError( ) method:

public boolean checkError( )

This method returns true if this print stream has ever encountered an error during its lifetime. Most of the time, you just ignore this, since print streams are only used in situations where exhaustive error checking is unnecessary.

There's also a protected setError( ) method you can use to signal an error from a subclass:

protected void setError( )

Once an error has been set, there's no way to unset it. Generally, once a PrintStream has encountered an error, all further writes to it silently fail. It's not the failure but the silence that makes PrintStream unsuitable for most applications.

Категории