how to avoid program termination when exception occur in java
I am doing an app for finding BPM in Android. Based on the input of the file null pointer exception and IO exception is getting thrown. When the exception occurs the program is terminated, even if I surround the code with a try/catch block. My requirement is that the program not terminate, and continue to the other parts.
My Code:
try {
mp3file.seekMP3Frame();
sourcefile = new File("/sdcard/a.mp3");
mp3file = new MP3File(sourcefile);
AbstractID3v2 tag = mp3file.getID3v2Tag();
text=tag.getFrame("TBPM").toString();
}
catch (NullPointerException e) {
System.out.println("null pointer exception");
}
catch (IOException e1) {
开发者_运维问答 System.out.println("IO exception");
}
........ // other coding
- If the error occurs between the try - catch block :
You are only catching 2 exceptions here (NullPointerException and IOException). Any other runtime exception between the try - catch block can still cause your program to crash. catch java.lang.Throwable to ensure all exceptions are catched.
- If the error doesn't occur between the try - catch block :
Look in the stacktrace for the line in your class where the error occurs, and implement "proper" error handling there.
If your application crashes, you'll always see a stacktrace in logcat. That stacktrace will be able to tell you what line of code is causing the crash.
Use finally
block in your code which is like
`try{
} catch{
} finally{
}`
finally will execute even if your try block throws exception or even if it doesn't.
精彩评论