gpt4 book ai didi

Java接口(interface)抛出异常但接口(interface)实现不抛出异常?

转载 作者:IT老高 更新时间:2023-10-28 20:39:49 26 4
gpt4 key购买 nike

我阅读了这段代码,其中接口(interface)抛出异常,但实现它的类没有抛出或捕获异常,这是为什么呢?在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.

— 斯坦·詹姆斯


作为 http://www.coderanch.com/t/399874/java/java/Methods-throwing-Exception-Interface 讨论的一部分

关于Java接口(interface)抛出异常但接口(interface)实现不抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15607060/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com