This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Java in General and the fly likes try/catch question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "try/catch question" Watch "try/catch question" New topic
Author

try/catch question

Ian Yang
Ranch Hand

Joined: Nov 27, 2001
Posts: 44
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

Joined: May 10, 2001
Posts: 3244
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.


Dave
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
Hello,

Just food for more thought...

Pretty self-explanatory, but are there any questions?
Good Luck,
-Dirk Schreckmann


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: try/catch question