Java Reference
In-Depth Information
}
}
}
catch
(
IOException
ex
)
{
errorLogger
.
log
(
Level
.
SEVERE
,
"Couldn't start server"
,
ex
);
}
catch
(
RuntimeException
ex
)
{
errorLogger
.
log
(
Level
.
SEVERE
,
"Couldn't start server: "
+
ex
.
getMessage
(),
ex
);
}
}
private
static
class
DaytimeTask
implements
Callable
<
Void
>
{
private
Socket
connection
;
DaytimeTask
(
Socket
connection
)
{
this
.
connection
=
connection
;
}
@Override
public
Void
call
()
{
try
{
Date
now
=
new
Date
();
// write the log entry first in case the client disconnects
auditLogger
.
info
(
now
+
" "
+
connection
.
getRemoteSocketAddress
());
Writer
out
=
new
OutputStreamWriter
(
connection
.
getOutputStream
());
out
.
write
(
now
.
toString
()
+
"\r\n"
);
out
.
flush
();
}
catch
(
IOException
ex
)
{
// client disconnected; ignore;
}
finally
{
try
{
connection
.
close
();
}
catch
(
IOException
ex
)
{
// ignore;
}
}
return
null
;
}
}
}
As well as logging,
Example 9-6
has also added
catch
blocks for
RuntimeException
that
cover most of the code and all of the network connections. This is strongly advisable in
network servers. The last thing you want is for your entire server to fall down just because
one request went down an unplanned code path and threw an
IllegalArgumentExcep
tion
. Usually when this happens that request is going to fail, but you can continue
processing other requests. If you're even more careful, you can send the client the ap‐
propriate error response. In HTTP, this would be a 500 internal server error.
Not every exception automatically turns into an error log entry. For example, if a client
disconnects while you're writing the time, that's an
IOException
. However, it's not a bug