user3229987
user3229987

Reputation: 11

Cant access variable that was initialized in try/catch statment

I am making a sound class for my game and after trying and trying i cant seem to get rid of the NullPointerException. This is happening because I cant access a variable in a try/catch statement.

Here is the code:

package util;

import java.applet.*;
import java.net.URL;

public class Sound 
{
    private AudioClip audio;
    private URL file;

    public Sound(String srcfile)
    {
        try 
        {
            this.file = new URL(srcfile);
        } 
        catch(Exception e){}

        this.audio = Applet.newAudioClip(file);
    }

    public void Play()
    {
        this.audio.play();
    }

    public void Loop()
    {
        this.audio.loop();
    }

    public void Stop()
    {
        this.audio.stop();
    }

    public AudioClip getAudio() 
    {
        return audio;
    }

    public void setAudio(AudioClip audio) 
    {
        this.audio = audio;
    }
}

Here is the error(no longer getting):

Exception in thread "main" java.lang.NullPointerException
    at sun.applet.AppletAudioClip.<init>(Unknown Source)
    at java.applet.Applet.newAudioClip(Unknown Source)
    at util.Sound.<init>(Sound.java:19)
    at main.Blocks.run(Blocks.java:38)
    at main.Blocks.main(Blocks.java:26)

After revising the old code her is the new code:

package util;

import java.applet.*;
import java.net.URL;

public class Sound 
{
    private AudioClip audio;

    public Sound(String srcfile)
    {
        try 
        {
            this.audio = Applet.newAudioClip(new URL("file://" + srcfile));
        } 
        catch(Exception e)
        {
            Log.log(e.getMessage(), Log.ERROR);
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void Play()
    {
        this.audio.play();
    }

    public void Loop()
    {
        this.audio.loop();
    }

    public void Stop()
    {
        this.audio.stop();
    }

    public AudioClip getAudio() 
    {
        return audio;
    }

    public void setAudio(AudioClip audio) 
    {
        this.audio = audio;
    }
}

I am calling Play(); but nothings happening

Here is how I'm calling the method:

Sound snd = new Sound("res/dev/sound.wav");
snd.Play();

Any help would be appreciated.

Upvotes: 1

Views: 195

Answers (1)

Durandal
Durandal

Reputation: 5663

It doesn't look like from the way your class is designed that there's any need for the file variable to exist outside the constructor. Something like this would probably serve well:

public Sound(String srcfile) {
        try {
            this.audio = Applet.newAudioClip(new URL(srcfile));
        } 
        catch(Exception e){
             //at least print the stack trace
             e.printStackTrace();
             //do some proper exception handling that makes sense for you app!
        }
}

Upvotes: 2

Related Questions