Reputation: 611
I'm new to the Java scene but currently working on an assigned assessment. I'm wondering if there is a way to catch an exception inside a class function and throw another exception so the function that called the class function doesn't need to know about the first exception thrown.
For example
public void foo() throws MasterException {
try {
int a = bar();
} catch (MasterException e) {
//do stuff
}
}
public void bar() throws MasterException, MinorException {
try {
int a = 1;
} catch (MinorException e) {
throw new MasterException();
}
}
I hope this example explains what I'm trying to achieve. Basically I want the calling function not to know about MinorException
.
Upvotes: 3
Views: 254
Reputation: 1945
Remove throws MasterException
from the declaration of method foo()
, the reason is clear that the MasterException has been ready catched SO would not get occurred anyway.
Remove , MinorException
from the declaration of method bar()
.
Upvotes: 0
Reputation: 3497
I would remove MasterException from foo() as you are catching it and as the other answers say, MinorException from bar().
Additionally, in case MasterException or MinorException is a subclass of RuntimeException, you do not need to declare it. See e.g. http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
Upvotes: 0
Reputation: 3059
Remove , MinorException
from the declaration of bar
and you are done.
I would also do:
throw new MasterException(e);
If MasterException
had a constructor that supported it (its standard it does, the Exception
class do).
Upvotes: 3
Reputation: 2251
Absolutely. You want to change this line:
public void bar() throws MasterException, MinorException
to this:
public void bar() throws MasterException
Everything else should work exactly how you've written it.
Upvotes: 1