Search code examples
javaexceptionthrow

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.


Solution

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