Is it possible to throw a Java exception through a calling method of a base class that does not throw exceptions?

This might be a ridiculous Java question about exception handling, but I have a user interface (Android activity) that is requesting services from my ContentProvider subclass. The subclass wants to throw some exceptions when the sd card is full, there is no sd card, network I / O errors, etc. However, when I code a CP subclass to exclude my exceptions, the compiler suggests adding exceptions for the CP class. Obviously, I don't want to change the base class, but I want the user interface to detect exceptions for the subclass.

Make sense? Is it possible? If not, is there a better template for my service subclass to return its return object back to the user interface?

+3
source share
3 answers

You only need to declare and catch the "checked exceptions". You do not need to declare or explicitly catch RuntimeExceptions. That way you can throw a RuntimeException and catch it, if you want, in the hierarchy.

+3
source

You can quit Unchecked exceptionswithout adding them to the prototype method.

An unchecked exception is any exception that inherits from RuntimeException. Is that what you wanted to do?

+8
source

RuntimeException, .

However, if we say that the empty exception specification is part of the contract of the base class methods. It is desirable that the subclasses satisfy the contract, so that subclass instances can be used in any code that uses the type of the superclass. (This is called the Liskov replacement principle .)

+6
source

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


All Articles