Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding Exceptions!

 
palla sridhar
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey!
I've a silly doubt regarding Exception.

When we're handling an exception, what will happen after the exception is caught. Will the JVM continue with the next line of code after doing what's in the catch clause or will it stop there doing what's in the catch clasue.

For e.g just look at this code:

import java.text.*;
import java.util.*;

class Dates3 {
public static void main(String[] args) {
Date d1 = new Date(1000000000000L);
try {
DateFormat[] dfa = new DateFormat[6];
dfa[0] = DateFormat.getInstance();
dfa[1] = DateFormat.getDateInstance();
dfa[2] = DateFormat.getDateInstance(DateFormat.SHORT);
dfa[3] = DateFormat.getDateInstance(DateFormat.MEDIUM);
dfa[4] = DateFormat.getDateInstance(DateFormat.LONG);
dfa[5] = DateFormat.getDateInstance(DateFormat.FULL);
dfa[6] = DateFormat.getDateInstance(DateFormat.DAY_OF_WEEK_FIELD); # 1
for (DateFormat df : dfa)
System.out.println(df.format(d1));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}


Here 1 produces an IllegalArgumentException and stops there.

Shouldn't the code continue as we're handling the exception ??
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Palla,

When an exception is thrown, control will basically transfer to the first catch clause that matches the exception. After the catch block finishes execution, control will then transfer to the finally block (if present), and then the next statement outside the entire try..catch statement. In other words:


will produce the output "1 3 4 5". As you can see, control does not return to the statement that threw the exception. This is similar to how most other popular OO languages perform exception handling, but you might find this confusing if you're used to a programming language that resumes at the point after the error/exception (e.g. BASIC's "ON ERROR ... RESUME NEXT" construct).
 
palla sridhar
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Kelvin!
You really solved my doubt..
Great response!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic