I am trying to add a custom throws clause to a method definied by an interface. This is not possible. How could I bypass it? Here is some 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 could throw my custom exception?
There are two types of exceptions, checked and unchecked. Any Throwable is either one or the other.
An example of a checked exception is IOException; probably the most (in)famous unchecked exception is NullPointerException.
Any checked exceptions that a method may throw must be declared in its throws clause. When you #Override a method (either implementing an interface method or overriding an inherited method from a superclass), certain requirements must be met, and one of them is that the throws clause must not cause a conflict. Simplistically speaking, subclasses/implementations can throw LESS, not MORE checked exceptions.
An unchecked exception is defined as RuntimeException and its subclasses, and Error and its subclasses. They do not have to be declared in a method's throws clause.
So in this particular case, if you want to throw a CustomException in an implementation of an interface method that does not list it in its throws clause, you can make CustomException extends RuntimeException, making it unchecked. (It can also extends any subclass of RuntimeException, e.g. IllegalArgumentException or IndexOutOfBoundsException may be more appropriate in some cases).
This will allow you to compile the code as you desire, but note that the choice between choosing checked vs unchecked exception should not be taken too lightly. This is a contentious issue for many, and there are many factors to consider other than just getting the code to compile the way you want it. You may want to consider a redesign of the interface rather than having implementors throwing various undocumented unchecked exceptions not specified by the interface contract.
References
JLS 11.2 Compile-Time Checking of Exceptions
JLS 8.4.6 Method Throws
A method that overrides or hides another method, including methods that implement abstract methods defined in interfaces, may not be declared to throw more checked exceptions than the overridden or hidden method.
Related questions
In Java, when should I create a checked exception, and when should it be a runtime exception?
When to choose checked and unchecked exceptions
The case against checked exceptions
See also
Effective Java 2nd Edition
Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors
Item 59: Avoid unnecessary use of checked exceptions
Item 60: Favor the use of standard exceptions
Item 61: Throw exceptions appropriate to the abstraction
Item 62: Document all exceptions thrown by each method
Workaround "solution"
If a redesign is impossible, then wrapping your CustomException in a RuntimeException (or its subclass) will "work". That is, instead of:
// ideal solution, not possible without redesign
#Override public static void someMethod() throws CustomException {
throw new CustomException();
}
//...
try {
someMethod();
} catch (CustomException e) {
handleCustomException(e);
}
You can, should you insist, do the following:
// 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
}
}
It needs to be reiterated that this is NOT a recommendable technique in general. You should fix the problem at the design level if at all possible, but barring that, this is indeed a possible workaround.
Throw a RuntimeException.
Related
I have a hard time to understand why the following code compiles, while it is not a subclass of exception:
class Test
{
public void run() throws IOException
{
System.out.println("Test");
}
}
class SubTest extends Test
{
//not a subclass of IOException, still compiles
public void run() throws RuntimeException
{
System.out.println("Test from sub");
}
}
class Sub2Test extends Test
{
//not a subclass of IOException, does not compile
public void run() throws Exception
{
System.out.println("Test from sub");
}
}
I understand RuntimeException is an unchecked exception, but I thought the rule was that it must be a subclass of the parent exception?
Imagine there is a caller which calls Test#run. In the declaration of Test#run, it says it might throw IOException, so the caller knows it can catch and handle it:
Test test = // it could be instance of SubTest of Sub2Test
try {
test.run();
} catch (IOException e) {
}
Then it's ok if SubTest does not throw IOException, the caller will not miss anything.
But if you throw some checked Exception like Sub2Test, since the caller does not know it until runtime, the called is not able to catch and handle it. So it should not be compiled.
"I understand RuntimeException is an unchecked exception, but I thought the rule was that it must be a subclass of the parent exception?"
That is the general rule, as specified in the JLS in section §11.2. Compile-Time Checking of Exceptions, which states (emphasis mine)
The throws clause of an overriding method may not specify that this method will result in throwing any checked exception which the overridden method is not permitted, by its throws clause, to throw (§8.4.8.3).
But that only applies to checked exceptions, and it also explicitly states that
The unchecked exception classes (§11.1.1) are exempted from compile-time checking.
So the compiler is going to ignore the fact that RuntimeException isn't a subclass of IOException.
I'm using Netbeans 8 IDE and I just came to this odd situation. Let's say I've a method in a class that throws and Exception and when I call that method Netbeans does not enforce the try catch. Sometimes an Exception may occur and it is not catch.
Why isn't Netbeans enforcing the try catch method?
Here's an example:
public class MyMethodClass {
public MyMethodClass() {}
public void someMethod() throws NullPointerException {
// do something
if(something == null) {
throw new NullPointerException();
}
// do something else
}
}
public class MyClass {
public MyClass() {
MyMethodClass mmc = new MyMethodClass();
// Here Netbeans does not force me to use a try catch, why?
mmc.someMethod();
}
}
NullPointerException is an unchecked exception, which means that you don't always need to catch it. Unchecked exceptions are those which extend RuntimeException or Error. The main purpose of these is for cases where there usually is no recovery; methods aren't required to declare unchecked exceptions either. This is perfectly valid:
public void throwNPE() {
throw new NullPointerException();
}
Here is one of Oracle's statements on checked vs unchecked exceptions.
NullPointerException is an unchecked exception (since it's a subclass of RuntimeException). You don't have to catch unchecked exceptions for the code to compile.
RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary
Because NullPointerException is an unchecked exception.
I have some few doubts on exceptions.
Can anyone tell me why java doesnt allow us to create Checked Exception in a Subclass while it allows Unchecked exception in a subclass
Below exampple throws Compile time error when I use 'throws IOException' , BUT it doesnt throw any error when I use 'throws ArithmeticException' in a subclass.. I just wanna know the actual reason behind it, so can you please?
Here is code (you will get compile time error)
package com.exception.test;
import java.io.IOException;
public class Parent {
void msg() {
System.out.println("Parent...");
}
public static void main(String[] args) {
Parent parent = new Child();
parent.msg();
}
}
class Child extends Parent {
void msg() throws IOException {
System.out.println("Child...");
}
}
//using unCheckedException
package com.exception.test;
import java.io.IOException;
public class Parent {
void msg() {
System.out.println("Parent...");
}
public static void main(String[] args) {
Parent parent = new Child();
parent.msg();
}
}
class Child extends Parent {
void msg() throws ArithmeticException {
System.out.println("Child...");
}
}
If a subclass method declares it can throw a checked exception that the parent doesn't, it breaks the Liskov substitution principle, which is one of the corner stones of object oriented programming.
Consider this bit of code, with Child.msg declared to throw a checked exception:
void doMsg(Parent p) {
p.msg();
}
The program semantics break if you pass in a child object because the checked exception is now neither being caught nor thrown: the exception is no longer "checked."
Since unchecked exceptions can be thrown everywhere, declaring to throw one serves no other purpose than documentation. Therefore it can be allowed safely.
The msg() method in your parent class can throw any unchecked exception it likes. Hence, if you explicitly declare that your child throws an unchecked exception, you're not actually altering the contract. Your child method may throw an ArithmeticException, but so might your parent method.
Checked exception can be narrowed down while overriding, but not can't be broaden. Unchecked exception need not be caught by the overridden methods
From the java specs
The checked exception classes named in the throws clause are part of
the contract between the implementor and user of the method or
constructor. The throws clause of an overriding method may not specify
that this method will result in throwing any checked exception which
the overridden method is not permitted, by its throws clause, to
throw.
Unfortunately, you have hit yet another pitfall of Java's misfeature known as Checked Exceptions. The error you are receiving is an actual problem that all Java professionals face: you are implementing a method with some code that happens to throw a checked exception not declared by the superclass method. The declared checked exceptions are a part of the Java method signature; you can reduce the list in a subclass, but you cannot expand it.
If this is more that just a "why" question, and you need a workaround, the standard idiom is
try {
...code that throws the checked exception...
} catch (TheCheckedException e) { throw new RuntimeException(e); }
This is called exception wrapping. If you have more than one or two undeclared checked exceptions, you can also use the opposite idiom, ensuring that all declared exceptions propagate transparently and all undeclared ones get wrapped:
try {
...code that throws various checked exceptions...
}
catch (DeclaredEx1 | DeclaredEx2 | RuntimeException e) { throw e;}
catch (Exception e) { throw new RuntimeException(e); }
when coding. try to solve the puzzle:
how to design the class/methods when InputStreamDigestComputor throw IOException?
It seems we can't use this degisn structure due to the template method throw exception but overrided method not throw it. but if change the overrided method to throw it, will cause other subclass both throw it.
So can any good suggestion for this case?
abstract class DigestComputor{
String compute(DigestAlgorithm algorithm){
MessageDigest instance;
try {
instance = MessageDigest.getInstance(algorithm.toString());
updateMessageDigest(instance);
return hex(instance.digest());
} catch (NoSuchAlgorithmException e) {
LOG.error(e.getMessage(), e);
throw new UnsupportedOperationException(e.getMessage(), e);
}
}
abstract void updateMessageDigest(MessageDigest instance);
}
class ByteBufferDigestComputor extends DigestComputor{
private final ByteBuffer byteBuffer;
public ByteBufferDigestComputor(ByteBuffer byteBuffer) {
super();
this.byteBuffer = byteBuffer;
}
#Override
void updateMessageDigest(MessageDigest instance) {
instance.update(byteBuffer);
}
}
class InputStreamDigestComputor extends DigestComputor{
// this place has error. due to exception. if I change the overrided method to throw it. evey caller will handle the exception. but
#Override
void updateMessageDigest(MessageDigest instance) {
throw new IOException();
}
}
In this case, your super class is not meant to throw an exception.
This is a case where your subclass is thus throwing an exception which is not expected by the overlying software architecture. Thus you can :
update all subclasses to throw exceptions.
wrap the entire Digestor class framework in a new class system.
(simplest) maintain the current code and simply wrap any exceptions you wish to throw in a RuntimeException.
RuntimeExceptions are the idiomatic way to throw exceptions in java which are not checked by the compiler or by method signatures, which occur somewhat unexpectedly.
Your requirements are schizophrenic.
You've got to decide whether the DigestComputor.updateMessageDigest method can, or can not throw IOException. If you want that to be possible, then you must add it to the signature in the base class. That is the only way to force the caller to do something about an IOException. But the downside is that you also force callers of the other subclasses to handle the IOException ... which won't occur.
You cannot create a method override that throws checked exceptions that the overridden method does not. That would break subtype substitutability, and Java doesn't allow it.
It it like a fork in the road. You have to decide to go one way or the other. You can't go both ways at the same time.
However there is a compromise (sort of):
public abstract class Base {
public abstract void method() throws IOException;
}
public class A extends Base {
public void method() throws IOException {
//
}
}
public class B extends Base {
public void method() { // Doesn't throw!!!
//
}
}
Now, if the caller knows that it has an instance of B it can do something like this:
Base base = ...
B b = (B) base;
b.method(); // No need to catch or propagate IOException
(IIRC, the ability to do this ... i.e. to reduce the exceptions thrown in an overriding method ... was added in Java 1.5.)
As someone else suggested, the simplest thing to do would be to simple wrap the real exception in a runtime exception. As a result, you don't have to declare the exception in your throws clause. If you're ambitious enough you can make your own subclass of RuntimeException and catch it at a higher level (this is what hibernate does, it catches all SQLExceptions thrown and wraps them in some subclass of DataAccessException which is a runtime exception).
Suppose I have interface I and two classes A and B that implement it.
The implementation of method f of this interface in A throws one set of exceptions and the implementation in B throws another set. The only common ancestor of these exceptions is java.lang.Exception. Is it reasonable to declare f throwing java.lang.Exception in this case? Any other alternatives?
The reason why I am asking is that on the one hand java.lang.Exception seems too general to me and one the other hand listing all exceptions seems impractical considering possible other implementations.
Example:
interface I {
void f() throws Exception;
}
class A implements I {
public void f() throws IOException {}
}
class B implements I {
public void f() throws InterruptedException {}
}
The reason for using an interface is to abstract away the implementation details.
By throwing these exceptions, you're exposing implementation details that probably should be abstracted away.
Perhaps it would be best to define a new exception. Then each implementation of f() would catch the exceptions it knows about and throw the new exception instead so you'd have:
interface I {
void f() throws MyException;
}
class A implements I {
public void f() throws MyException {
try {
...
} catch (IOException e) {
throw new MyException(e);
}
}
}
class B implements I {
public void f() throws MyException {
try {
...
} catch (InterruptedException e) {
throw new MyException(e);
}
}
}
By wrapping the implementation exception, you're still exposing it to the caller and that can bite you when you're calling remote methods. In those cases you need to do more work to return useful information in a generic way.
Edit
There seems to be a bit of a dispute going on about the correct approach.
When we call f(), we'll need code like:
I instanceOfI = getI();
try {
instanceOfI.f();
}
catch ( /* What should go here ? */ )
It comes down to what is a good Exception class to put in the catch block.
With OP's original code we could catch Exception and then maybe try to see which subclass we have, or not depending on requirements. Or we could individually catch each subclass but then we'd have to add catch blocks when new implementations throw different exceptions.
If we used Runtime exceptions it would come to much the same thing except that we could alternatively defer the exception handling to a caller method without even giving the possibility of exceptions any thought.
If we used my suggestion of using a new, wrapped exception then this means we have to catch MyException and then try to see what additional information is available. This essentially becomes very like just using an Exception, but requires extra work for the limited benefit of having a bespoke exception that can be tailored to the purpose.
This seems a bit backward. You should be throwing exceptions that are relevant and possibly specific to your interface, or not at all. Change the implementations to wrap a common Exception class (although not Exception itself). If you can't deal with this you may want to wrap the Exceptions in the implementations with a RuntimeException.
You could just declare the exceptions you throw
void f() throws IOException, InterruptedException;
If you use a decent IDE, it will correct this for you. I just throw the exception in the method, which the IDE gives the optionsto add to the method clause and its interface.