1

Basically i'm writing a game in Java where i want the program to tell the user that he can't move right or left if that move will cause the player to move out of the array, which means this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Game.printmap(Game.java:58)
at Game.main(Game.java:17)

The Array is the map where the character can move and i want to avoid it from going outside of it. It is the game world where the player can move inside.

Is there a way to make my program ask for input again if the player choice implies an OutOfBounds error?

Thank you

1 Answers1

3

Well, the best way to deal with this is to fix the error that caused the exception to be thrown in the first place.

That said, you could always write a top-level try catch block. This will catch any exceptions that weren't handled elsewhere.

public static void main(String args[])
{
    while (userDidNotExit)
    {
        try
        {
            // execute entry point of program here.
        }
        catch (Exception e)
        {
            // perform some sort of recovery here.
            // 
        }
    }
}
Robert Harvey
  • 200,592