Reputation: 3
I have a basic question in Java:
I have two methods: functionA
& functionB
. functionA
calls functionB
, and functionB
rise an exception. The call to functionB
is in try scope of functionA
.
Now I also want that functionA
will go to it catch scope.
There is any way to do that?
Upvotes: 0
Views: 5800
Reputation: 1235
Not sure if this is what you want
void functionB() throws MyException {
try{
.....
}Catch(MyException e){
//do something here;
throw e;
}
}
void functionA() {
try {
functionB();
} catch (MYException e) {
//do something else to A here
}
}
Upvotes: 0
Reputation: 328598
If an exception is thrown in methodB
and you catch it, one way to propagate it to methodA
is to rethrow it:
void methodB() throws SomeException {
try {
//Something that can throw SomeException
} catch (SomeException e) {
//rethrow e
throw e;
}
}
void methodA() {
try {
methodB();
} catch (SomeException e) {
//this block will run if methodB throws SomeException
}
}
But if you need that, you probably should not catch the exception in methodB
at all and just let it propagate automatically to methodA
:
void methodB() throws SomeException {
//Something that can throw SomeException: don't catch it
}
void methodA() {
try {
methodB();
} catch (SomeException e) {
//this block will run if methodB throws SomeException
}
}
Upvotes: 2
Reputation: 354406
Actually, that is how it works usually, provided that functionB
doesn't catch the exception itself. Exceptions, when thrown, bubble up the call stack until a matching catch
block is found.
Upvotes: 0