I read this code where the interface throws an exception, but the class which implements it doesn't throw one or catch one, why is that? Is it legal or safe in java?
import java.rmi.*; public interface MyRemote extends Remote { public String sayHello() throws RemoteException; } import java.rmi.*; import java.rmi.server.*; public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote{ public String sayHello() { return "Server says, 'Hey'"; } public MyRemoteImpl() throws RemoteException {} public static void main (String[] args) { try { MyRemote service = new MyRemoteImpl(); Naming.rebind("RemoteHello", service); } catch(Exception ex) { ex.printStackTrace(); } } }
Yes, the abstract methods of an interface can throw an exception.
Yes, you can throw and exception from an abstract class.
Exception HierarchyThe exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. Errors are abnormal conditions that happen in case of severe failures, these are not handled by the Java programs.
What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console. The message typically includes: name of exception type.
If a Java method overrides another in a parent class, or implements a method defined in an interface, it may not throw additional checked exceptions, but it may throw fewer.
public class A { public void thrower() throws SQLException {...} } public class B extends A { @Override public void thrower() throws SQLException, RuntimeException, NamingException {...} }
SQLException
is fine; it's declared in the overridden method. It could even be replaced by a subclass like SerialException
.
RuntimeException
is fine; those can be used anywhere.
NamingException
is illegal. It isn't a RuntimeException
, and isn't in A
's list, even as a subtype.
A general rule of implementing and extending is you can make your new class or interface "less restrictive" but not "more restrictive". If you think of the requirement to handle an exception as a restriction, an implementation that doesn't declare the exception is less restrictive. Anybody who codes to the interface will not have trouble with your class.
— Stan James
As part of the discussion at http://www.coderanch.com/t/399874/java/java/Methods-throwing-Exception-Interface
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With