Benji
Benji

Reputation: 611

Catching Exceptions and Rethrowing

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

Answers (5)

C.c
C.c

Reputation: 1945

  1. 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.

  2. Remove , MinorException from the declaration of method bar().

Upvotes: 0

user3001
user3001

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

esej
esej

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

Martin Prakash
Martin Prakash

Reputation: 66

Just remove the MinorException from throws clause of bar().

Upvotes: 1

Erica
Erica

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

Related Questions