This site requires JavaScript, please enable it in your browser!
Greenfoot back
RcCookie
RcCookie wrote ...

2020/1/11

It works, but why?

RcCookie RcCookie

2020/1/11

#
I tried to create a game where the object simply looks in the direction of the mouse. Therefore, I used the coordinates of mouseInfo and just put it into a turnTowards()-method. Once I started the programm, I got a NullPointerException. I put the method in a try/catch block, because I thought, it only occured in the first frame, and it works. But when I printed the exception I figured out it called it every frame. I just wonder why it works, since there is only a single line of code, where the exception has to be thrown, and that should mean, that it was not exectuted(?) My Code:
public void aim(){
        try{
           turnTowards(Greenfoot.getMouseInfo().getX(), Greenfoot.getMouseInfo().getY());
        }
        catch(Exception e){}
}
I´d be happy if someone understanding me could teach me why it works;-)
danpost danpost

2020/1/11

#
If an exception is thrown within a try block, the catch block is executed and the simulation continues to run. In fact, that is the purpose of the try-catch structure: to allow a program to make corrective steps should a particular error occur. Also, giving the program a chance to end smoothly and gracefully, possibly giving feedback as to what occurred (instead of ending abruptly). Usually the structure is used for things that cannot be readily checked on (for example, file operations). You have no need to use it as you can easily check whether the MouseInfo object is null or not. You can change your method to this:
public void aim()
{
    MouseInfo mouse = Greenfoot.getMouseInfo();
    if (mouse == null) return;
    turnTowards(mouse.getX(), mouse.getY());
}
RcCookie RcCookie

2020/1/11

#
I know the general purpose of a try/catch-block, but in this case, the exception is thrown every frame. Nevertheless the Actor does look towards the mouse, witch is what I don’t understand: if there is nothing in mouseInfo, why can it point in the right direction, or the other way around: why does the execution throw an error, if there is a value stored?
danpost danpost

2020/1/11

#
RcCookie wrote...
I know the general purpose of a try/catch-block, but in this case, the exception is thrown every frame. Nevertheless the Actor does look towards the mouse, witch is what I don’t understand: if there is nothing in mouseInfo, why can it point in the right direction, or the other way around: why does the execution throw an error, if there is a value stored?
The exception is NOT thrown every frame.
You need to login to post a reply.