Game Development Reference
In-Depth Information
This code handles a variety of cases before actually accessing the array. If id is out of range or isn't
an integer number (in other words, the floor function of the number doesn't return the number itself),
the method stops execution and throws an exception (which in this case is a string value). To do
something with the error, you can call the get function in a try - catch block:
try {
var myGameState = GameStateManager.get(someId);
// do something with the game state
} catch (e) {
console.log("Error: " + e);
}
As you can see, the method call that may throw an exception is in the body of a try instruction.
If there is an exception, the program continues in the body of the catch part. If there is no exception,
then the catch body isn't executed.
In the catch part, the exception is caught. Behind the word catch is a parameter that contains the
object being thrown. In the previous example, the get method can throw a string that contains the
error message. This isn't the best way to do it. More complex programs generally define a hierarchy
of exception classes. An instance of such a class can contain information such as the time at which
the exception occurred and in which method, the parameter values of that method, a custom error
message, and so on. Different classes can then be used to represent different types of errors.
Because the games in this topic are simple, they don't touch on handling errors this way. But it's a
good idea to think about how you want to deal with errors in your games, and perhaps exceptions
can help you do it in a more robust way.
Let's go back to the try instruction. You can place multiple instructions in the body of that
instruction. But as soon as an exception occurs, the execution is halted and the body of the catch
is executed. The remaining instructions after the try may therefore assume that there was no
exception if they're executed.
The bodies of the try and the catch part need to be between braces, even if there is only a single
instruction in the body. This is a bit illogical, given that the braces may be omitted in, for example,
if and while instructions.
After the catch part, it's possible to place a finally part, which is executed whether an exception of
a certain kind is caught or not. For example:
try {
openServerConnection(ipAddress);
// communicate with the server
...
}
catch (e) {
console.log("Error while communicating with the server: " + e);
finally {
// always close the server connection
closeServerConnection();
}
 
Search WWH ::




Custom Search