Java Reference
In-Depth Information
To simplify things, our code catches the DatabaseWriteException and just logs the
error—basically just ignoring it. That can be a very “beginner's” way to handle
exceptions, though, and you shouldn't always just ignore them. Instead, the
question to ask yourself is “whose problem is it, and who can fix it?”
Normally, code that you're calling in a library has no idea what you're using
it for. When something bad happens, it doesn't know what you need to do to
handle the problem. Should the whole server exit? Should you return an error
to the user? Do you need to change some variables and clean up whatever
you were trying to do? Since the library code doesn't know, it doesn't try to
fix it. It just raises an exception—it throws up its hands and gives up.
When dealing with exceptions, you have two choices. You can either accept
the responsibility for dealing with any errors and catch and handle the
exception yourself, or you can throw up your hands as well, and pass the
exception up to the caller. To pass the exception up, you just declare that
your function also throwsDatabaseWriteException (or whatever the actual exception
type is). You don't need any try / catch at all; now it's someone else's problem.
In theory, however, exceptions should be used only for exceptional things. If
you went to spawn a cow and instead got a creeper, that would be exceptional:
an unexpected disaster. If you just added a player to a list of players and the
length of the list was still zero, that would indicate a disaster in progress.
But trying to search for something that isn't in the database, for example,
isn't a disaster. It's a common occurrence. So in that case you might want to
catch the exception and ignore it.
And what happens if you fail when trying to write data to the database, as
we're doing here? That might mean there's a more serious problem—you
might be out of disk space on the server, for instance. What should you do?
If it were me, I'd want to shut down the server as gracefully as possible. A
dead program does a lot less damage than a broken program that's still run-
ning. When writing code for most professional systems, you'll find that's
almost always the best action to take: fail quickly and loudly.
But this isn't our server necessarily; we've just made a plugin that someone
else is running, and it would be rude of us to shut down their server just
because we can't write a file. So in this case, we'll log an error message to the
Minecraft console and struggle on.
 
 
Search WWH ::




Custom Search