how to avoid program termination when exception occur in java - 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.

Related

Java - catch/rethrow behavior [duplicate]

This question already has answers here:
Exception thrown in catch and finally clause
(12 answers)
Closed 1 year ago.
I have this piece of Java code.
void convertFile() {
try{
.....
}catch (Exception e) {
logError("Error in convertJsonFile", e);
throw e;
}finally{
if (writer!=null) {
writer.close();
writer = null;
}
if (fos!=null) {
fos.close();
fos = null;
}
ms2 = System.currentTimeMillis();
logInfo(String.format("Time elapsed: %d seconds.", ((ms2-ms1)/1000)));
logInfo("File conversion complete.");
}
return f + "_changed.xml";
}
The catch block logs and rethrows the Exception.
But it seems the finally block also throws a RuntimeException.
Will the finally block be executed if the catch block rethrows Exception as done here?
If I remember correctly finally block will be executed even in this case.
OK if so... what will happen if we enter the catch block (it rethrows), then we enter the finally block, and the finally block also throws a RuntimeException at this line writer.close(); ? Which exception will be thrown from this whole method - the rethrown one from the catch block, or the RuntimeException from the finally block?!
I think the RuntimeException will be the final outcome of the method and we will never reach the line in the catch block which rethrows. Because I guess the line which rethrows is executed after the finally block. But I am not sure. I got really confused.
Could someone clear my doubts here?
Seems I have forgotten some of these details.
And I have no decent access to the logs, they are in Elastic/Kibana and access to them is a real pain.
Yes, finally block will be executed
The exception from finally block will be thrown in this case. Thus, exception from catch block will be lost.

Can I throw exception again when I catch it?

try{
WebElement naimi_logo = firefox.findElement(By.xpath("//a[#href=\"/astana/\"]/img") ) ;
naimi_logo.click();
}catch( IllegalStateException e){
throw new IllegalStateException("this image is not clickable!") ;
}
catch(NoSuchElementException e){
throw new NoSuchElementException("logo is not found!!") ;
}
Should I really throw exception in my catch block? Or is it better to just print what happened to console?
Does the order of the catches matter?
It looks like your intent is to add more information when an exception occurs. In that case what you are doing is fine. However you will lose complete stack trace for the underlying exception.
You can use:
java.lang.RuntimeException.RuntimeException(String, Throwable)
If you don't want to lose the stack trace of original exception.
Can I throw exception again when I catch it?
To just rethrow the exception you do
throw e;
On the other hand this is equivalent of not catching the exception at all and let it propagate.
Perhaps you want to give the exception a better message, but keep the exception class. You would then typically do:
}catch( IllegalStateException e){
throw new IllegalStateException("this image is not clickable!", e);
}
catch(NoSuchElementException e){
throw new NoSuchElementException("logo is not found!!", e);
}
Should I really throw exception in my catch block?
This depends on what your method is intended to do. Your options are basically
Catch and handle the exception gracefully. Your method can complete normally even in case of an "internal" exception.
Catch the exception and wrap it in another exception more suitable for your level of abstraction.
Let the exception propagate.

Java exception not caught?

I have a small theoretical problem with try-catch constructions.
I took a practical exam yesterday about Java and I don't understand following example:
try {
try {
System.out.print("A");
throw new Exception("1");
} catch (Exception e) {
System.out.print("B");
throw new Exception("2");
} finally {
System.out.print("C");
throw new Exception("3");
}
} catch (Exception e) {
System.out.print(e.getMessage());
}
The question was "what the output will look like?"
I was pretty sure it would be AB2C3, BUT suprise suprise, it's not true.
The right answer is ABC3 (tested and really it's like that).
My question is, where did the Exception("2") go?
From the Java Language Specification 14.20.2.:
If the catch block completes abruptly for reason R, then the finally block is executed. Then there is a choice:
If the finally block completes normally, then the try statement completes abruptly for reason R.
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
So, when there is a catch block that throws an exception:
try {
// ...
} catch (Exception e) {
throw new Exception("2");
}
but there is also a finally block that also throws an exception:
} finally {
throw new Exception("3");
}
Exception("2") will be discarded and only Exception("3") will be propagated.
Exceptions thrown in finally block suppress the exception thrown earlier in try or catch block.
Java 7 example: http://ideone.com/0YdeZo
From Javadoc's example:
static String readFirstLineFromFileWithFinallyBlock(String path)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}
However, in this example, if the methods readLine and close both throw
exceptions, then the method readFirstLineFromFileWithFinallyBlock
throws the exception thrown from the finally block; the exception
thrown from the try block is suppressed.
The new try-with syntax of Java 7 adds another step of exception suppression: Exceptions thrown in try block suppress those thrown earlier in try-with part.
from same example:
try (
java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
) {
for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) {
String newLine = System.getProperty("line.separator");
String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine;
writer.write(zipEntryName, 0, zipEntryName.length());
}
}
An exception can be thrown from the block of code associated with the
try-with-resources statement. In the above example, an exception can
be thrown from the try block, and up to two exceptions can be thrown
from the try-with-resources statement when it tries to close the
ZipFile and BufferedWriter objects. If an exception is thrown from the
try block and one or more exceptions are thrown from the
try-with-resources statement, then those exceptions thrown from the
try-with-resources statement are suppressed, and the exception thrown
by the block is the one that is thrown by the
writeToFileZipFileContents method. You can retrieve these suppressed
exceptions by calling the Throwable.getSuppressed method from the
exception thrown by the try block.
In code from question, each block is plainly discarding the old exception, not even logging it, not good when you are trying to resolve some bugs:
http://en.wikipedia.org/wiki/Error_hiding
Since throw new Exception("2"); is thrown from catch block and not try, it won't be caught again.
See 14.20.2. Execution of try-finally and try-catch-finally.
This is what happening:
try {
try {
System.out.print("A"); //Prints A
throw new Exception("1");
} catch (Exception e) {
System.out.print("B"); //Caught from inner try, prints B
throw new Exception("2");
} finally {
System.out.print("C"); //Prints C (finally is always executed)
throw new Exception("3");
}
} catch (Exception e) {
System.out.print(e.getMessage()); //Prints 3 since see (very detailed) link
}
Your Question is very obvious, and the answer is simple to the same extent..
The Exception object with message as "2" is overwritten by the Exception object with message as "3" .
Explanation :
When an Exception occur, its object it thrown to catch block to handle. But when exception occur in catch block itself, its object is transferred to OUTER CATCH Block(if any) for exception Handling. And Same happened Here. The Exception Object with message "2" is transferred to OUTER catch Block . But wait.. Before leaving inner try-catch block it HAS TO EXECUTE FINALLY. Here occurred the change we are concerned about. A new EXCEPTION object(with message "3") is thrown out or this finally block which replaced the already thrown Exception object(with message "2").As a result of which, when the message of Exception object is printed , we got overridden value i.e. "3" and not "2".
Keep Remember :Only one exception object can be handled by on CATCH block.
The finally block always runs. Either you return from inside the try block or an exception is thrown. The exception thrown in the finally block will override the one thrown in the catch branch.
Additionally, throwing an exception will not cause any output by itself. The line throw new Exception("2"); will not write anything out.
According to your code:
try {
try {
System.out.print("A");
throw new Exception("1"); // 1
} catch (Exception e) {
System.out.print("B"); // 2
throw new Exception("2");
} finally { // 3
System.out.print("C"); // 4
throw new Exception("3");
}
} catch (Exception e) { // 5
System.out.print(e.getMessage());
}
As you can see here:
print A and throws exception # 1;
this exception has caught by catch statement and print B - # 2;
block finally # 3 executes after try-catch (or only try, if hadn't occurred any exception) statement and prints C - # 4 and thrown new exception;
this one has caught by external catch statement # 5;
Result is ABC3. And 2 is omitted at the same way as 1

Java catching exceptions and subclases

Hello,
In Java if a method like BufferedReader.read() says it can throw an IOException and I try to catch a FileNotFoundException and an IOException in two catch blocks, what catch blocks will be entered if the file doesn't exist?
Does it enter only the most specific or both?
The first coded catch that matches the exception will be entered.
Edited to incorporate comment from Azodius
For example:
try {
bufferedReader.read();
} catch (FileNotFoundException e) {
// FileNotFoundException handled here
} catch (IOException e) {
// Other IOExceptions handled here
}
This following code does not compile:
try {
bufferedReader.read();
} catch (IOException e) {
// All IOExceptions (and of course subclasses of IOException) handled here
} catch (FileNotFoundException e) {
// Would never enter this block, because FileNotFoundException is a IOException
}
Compiler message says:
Unreachable catch block for FileNotFoundException. It is already handled by the catch block for IOException
Only the first catch block encountered where the exception type of the catch block matches the type of the exception being thrown will be run (more specifically, the first catch block where (e instaceof <exception type>)==true will be run). None of the other catch blocks will be run.
For example
try{
BufferedReader.read();
}
catch(FileNotFoundException e){System.out.println("FileNotFoundException");}
catch(IOException e){System.out.println("IOException");}
Will print FileNotFoundException if BufferedReader.read() throws a FileNotFoundException.
Note that the following doesn't actually compile:
try{
BufferedReader.read();
}
catch(IOException e){System.out.println("IOException");}
catch(FileNotFoundException e){System.out.println("FileNotFoundException");}
because Java realizes that it is not possible for the FileNotFoundException to be caught because all FileNotFoundExceptions are also IOExceptions.
The first one which is suitable for that type of exception (and only that). So if you catch the two exception types above in the order you list them, a FileNotFoundException will be caught.
Specific exception is caught first. and it's a compile time error if generic exception is caught befor specific one.

handling java exception

This questions is related to java exceptions, why are there some cases that when an exception is thrown the program exits even though the exception was caught and there was no exit() statement?
my code looks something like this
void bindProxySocket(DefaultHttpClientConnection proxyConnection, String hostName, HttpParams params)
{
if (!proxyConnection.isOpen())
{
Socket socket = null;
try {
socket = new Socket(hostName, 80);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
proxyConnection.bind(socket, params);
}
catch(IOException e)
{
System.err.println ("couldn't bind socket");
e.printStackTrace();
}
}
}
and then
I call this method like this:
bindProxySocket(proxyConn, hostName, params1);
but, the program exits, although I want to handle the exception by doing something else, can it be because I didn't enclose the method call within a try catch clause? what happens if I catch the exception again even though it's already in the method? and what should I do if i want to clean resources in the finally clause only if an exception occurs and otherwise I want to continue with the program? I am guessing in this case I have to include the whole piece of code until I can clean the resources with in a try statement or can I do it in the handle exception statement?
some of these questions are on this specific case, but I would like to get a thorough answer to all my questions for future reference. thanks
edit:
java.net.UnknownHostException: www.dsewew324f.com
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at homework3.Proxy.bindProxySocket(Proxy.java:666)
at homework3.Proxy$3.handle(Proxy.java:220)
at org.apache.http.protocol.HttpService.doService(HttpService.java:293)
at org.apache.http.protocol.HttpService.handleRequest(HttpService.java:212)
at homework3.Proxy.start(Proxy.java:472)
at homework3.Proxy.main(Proxy.java:1282)
Exception in thread "main" java.lang.IllegalArgumentException: Socket may not be null
at org.apache.http.impl.DefaultHttpClientConnection.bind(DefaultHttpClientConnection.java:80)
at homework3.Proxy.bindProxySocket(Proxy.java:674)
If
socket = new Socket(hostName, 80);
throws an exception then socket will be null and
proxyConnection.bind(socket, params);
will throw a NullPointerException, which you do not catch.
Are you sure the exception was caught? Your catch block only catches certain exceptions. A Runtime exception could be getting thrown which would not be caught..
Could it be that your program is simply coming to it's natural conclusion (exits from the main method)?
If your program is exiting because of an exception thrown from the main method then it should be printed to the console. Can you provide this stack trace?
May be that proxyConn is null, and because
if (!proxyConnection.isOpen())
it is not in a try/catch block it may generate an unhandled exception that causes your program to exit.
To answer some of your questions: what happens if I catch the exception again even though it's already in the method?
To put it simply, you can't. Once an exception is caught once, it is no longer on the top of the stack so any further attempts to catch it will fail
what should I do if i want to clean resources only if an exception occurs and otherwise I want to continue with the program?
If you want to do some action, any action, only when an exception occurs you should do this in your catch block.
I am guessing in this case I have to include the whole piece of code until I can clean the resources with in a try statement or can I do it in the handle exception statement?
I already answered this question with the one above :P
Like I said in my comment on marcus' post you should put a try catch around the call to the function itself to ensure that any other exceptions are being caught. You can figure out what to do from there when you know what exceptions aren't being caught.
try{
bindProxySocket(proxyConn, hostName, params1);
}
catch(Exception e){
e.printStackTrace():
}
You shouldn't continue the code after an exception which may cause that the code cannot continue.
Rewrite your code as follows:
Socket socket = null;
try {
socket = new Socket(hostName, 80);
try
{
proxyConnection.bind(socket, params);
}
catch(IOException e)
{
System.err.println ("couldn't bind socket");
e.printStackTrace();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Better practice is just to let that exception go and declare a throws in your method. You should only handle the exception where it makes sense to handle it. Don't suppress the exceptions by just printing the trace and then continuing with the program flow.

Categories

Resources