Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 881
Benji Avatar asked May 29 '26 02:05

Benji


2 Answers

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

like image 150
esej Avatar answered May 31 '26 17:05

esej


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.

like image 32
Erica Avatar answered May 31 '26 18:05

Erica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!