debugjavaMinor
Exception handling and general check in Java
Viewed 0 times
handlingexceptionjavageneralandcheck
Problem
Are the
catch statements ok or must I put in a println()? In general, is the code good-looking enough?public void music(String song) {
try {
File soundFile = new File(song);
AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);
// load the sound into memory (a Clip)
DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(sound);
// play the sound clip
clip.start();
}
catch (IOException e) {
}
catch (LineUnavailableException e) {
}
catch (UnsupportedAudioFileException e) {
}
}Solution
Must I put in System.out.println(); so I can know which one it is?
That would be one approach, and it would certainly be better than your current approach, which is silently failing. In case something goes wrong, this will make it very difficult to find out the problem.
If you get an exception, you should first try to think of recovering from it right then and there.
If that is not possible, I would just trow it upwards, and let the calling method handle it. In your case for example by playing a default song, or skipping to the next song, etc.
If all else fails, you should report a helpful and detailed error message to the end user. For debugging purposes, you should also print the exact exception - including stacktrace - to the console.
Just swallowing the exception is pretty much never the correct approach.
Misc
That would be one approach, and it would certainly be better than your current approach, which is silently failing. In case something goes wrong, this will make it very difficult to find out the problem.
If you get an exception, you should first try to think of recovering from it right then and there.
If that is not possible, I would just trow it upwards, and let the calling method handle it. In your case for example by playing a default song, or skipping to the next song, etc.
If all else fails, you should report a helpful and detailed error message to the end user. For debugging purposes, you should also print the exact exception - including stacktrace - to the console.
Just swallowing the exception is pretty much never the correct approach.
Misc
// play the sound clipisn't really a helpful comment, it's pretty obvious from the code already
- If you handle all exceptions the same way anyways (in your case ignoring them), you can just catch the generic
Exception.
- as barq said, your indentation is partly off.
musicis a little generic as a method name. maybeplaySong, orplayClip
Context
StackExchange Code Review Q#80021, answer score: 9
Revisions (0)
No revisions yet.