Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

try/catch question

 
Ian Yang
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a java code, it has following:
public void method_A() {
try {
...
...
}catch(Exception_1 e ) {
...
}catch(Exception_2 e) {
...
}
}
Now if I have another method called "method_B()" in the same class:

public void method_B() {
method_A();
}
this method_B only calls method_A. Then how should I handle the exception in this method, which one(s) of the following is(are) correct ?
1. public void method_B() throws Exception_1, Exception_2 {
method_A();
}
2. public void method_B() {
try {
method_A();
}catch(Exception_1 e ) {
...
}catch(Exception_2 e) {
...
}
}
3. public void method_B() {
mthod_A();
}
Thanks,
Ian
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ian
If both of the exceptions that A can throw are caught and handled in A then you dont need to do anything special in B to account for them.
The compiler will look at A to see if it throws any exceptions that B might need to cach if so then it tells you that there is an uncaught exception, in your case if A can only throw the two checked exceptions then the compiler will not complain becasue you ahve them both caught in A (unless A then rethrows the same or a different exception).
You last method would the correct one.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

Just food for more thought...

Pretty self-explanatory, but are there any questions?
Good Luck,
-Dirk Schreckmann
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic