Java接口抛出异常但接口实现不抛出异常? [英] Java interface throws an exception but interface implementation does not throw an exception?

查看:42
本文介绍了Java接口抛出异常但接口实现不抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过这段代码,其中接口抛出异常,但实现它的类没有抛出或捕获异常,这是为什么呢?在java中它是合法的还是安全的?

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.

—斯坦·詹姆斯

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

这篇关于Java接口抛出异常但接口实现不抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆