Java接口引发异常,但接口实现不会引发异常? [英] Java interface throws an exception but interface implementation does not throw an exception?
问题描述
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(){
returnServer said,'Hey';
}
public MyRemoteImpl()throws RemoteException {}
public static void main(String [] args){
try {
MyRemote service = new MyRemoteImpl();
Naming.rebind(RemoteHello,服务);
} catch(Exception ex)
{
ex.printStackTrace();
}
}
}
实现和扩展的一般规则是,您可以使您的新类或接口限制较少,但不能限制更多。如果您想到处理异常作为限制的要求,则不声明异常的实现限制较少。任何编码到界面的人都不会遇到你的班级麻烦。
— Stan James
作为 http://www.coderanch.com/t/399874/java/java/Methods-throwing-Exception-Interface
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();
}
}
}
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
这篇关于Java接口引发异常,但接口实现不会引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!