Throw custom exception to interface implementation method

I am trying to add a custom clause throwsto a method defined by an interface. It's impossible. How could I get around him? Here is the code:

private void sendRequestToService(final ModuleRequest pushRequest) 
{

    ServiceConnection serviceConnection = new ServiceConnection()
    {

        public void onServiceConnected(ComponentName name, IBinder service) 
        {

            try
            {

                //some lines..

            } catch (RemoteException e)
            {
                throw new RuntimeException(new UnavailableDestException()) ;
            }
        }


    };

}

Any idea how I can throw my own exception?

+3
source share
2 answers

There are two types of exceptions: checked and unchecked. Any Throwableis either one or the other.

An example of a checked exception is IOException; probably the most (in) famous exception thrown is NullPointerException.

, throw throws. @Override ( interface, ), , , throws . , / LESS, MORE .

RuntimeException , Error . throws.

, , throw a CustomException interface, throws, CustomException extends RuntimeException, . ( extends RuntimeException, , IllegalArgumentException IndexOutOfBoundsException ).

, , . , , , , . , interface , , interface.

.

  • Java 2nd Edition
    • 58: .
    • 59: .
    • 60:
    • 61: ,
    • 62: , .

"

, CustomException RuntimeException ( ) "". :

// ideal solution, not possible without redesign

@Override public static void someMethod() throws CustomException {
    throw new CustomException();
}

//...
try {
    someMethod();
} catch (CustomException e) {
    handleCustomException(e);
}

, , :

// workaround if redesign is not possible
// NOT RECOMMENDED!

@Override public static void someMethod() {
    throw new RuntimeException(new CustomException());
}

//...
try {
    someMethod();
} catch (RuntimeException e) { // not catch(CustomException e)

    if (e.getCause() instanceof CustomException) {
        handleCustomException((CustomException) e.getCause());
    } else {
        throw e; // preserves previous behavior
    }

}

, . , , , , .

+12

RuntimeException.

+4

Source: https://habr.com/ru/post/1758606/


All Articles