Elimination and reuse

I am new to the Java scene, but am currently working on a designated assessment. I am wondering if there is a way to catch an exception inside a class function and throw another exception, so a function called a class function should not know about the first exception.

for instance

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();
    }
}

Hope this example explains what I'm trying to achieve. Basically, I want the calling function not to know about MinorException.

+3
source share
5 answers

Remove , MinorExceptionfrom the ad barand you're done. I would do too:

throw new MasterException(e);

If you MasterExceptionhad a constructor that supported it (it does its standard, class Exceptiondo).

+3
source

. :

public void bar() throws MasterException, MinorException

:

public void bar() throws MasterException

, .

+1

MinorException throws bar().

+1

I would remove MasterException from foo () as you would catch it, and as other answers say, MinorException from bar ().

In addition, if MasterException or MinorException is a subclass of RuntimeException, you do not need to declare it. See http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html

0
source
  • Remove throws MasterExceptionfrom the method declaration foo(), the reason is that the MasterException was ready, and SO did not happen anyway.

  • Remove , MinorExceptionfrom the method declaration bar().

0
source

All Articles