Java接口引发异常,但接口实现不会引发异常? [英] Java interface throws an exception but interface implementation does not throw an exception?

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

问题描述

我读了这个代码,在这个接口抛出一个异常,但实现它的类不会抛出一个或者是catch一个,为什么呢?在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(){
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屋!

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