Java中抛出异常的方法 [英] Method overriding in Java throwing exceptions

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

问题描述



我有一段代码:

  public class ExceptionClass {
void m()throws SQLException {}

}

扩展ExceptionClass {

void m()throws Exception {}
}

异常Exception异常与ExceptionClass.m()中的throws子句不兼容。



如果我写为:

  public class ExceptionClass { 
void m()throws SQLException {}
}

扩展ExceptionClass {

void m()throws RuntimeException {}
}

这个没有给出任何错误和方法也被正确地覆盖。
经过一些分析,我以为可能是因为SQLException从Exception类扩展,所以我们不能在子类中替换SQLException和Exception(我们正在改变覆盖方法的签名)。



但是我这样做了:

  public class ExceptionClass {
void m )throws NullPointerException {}
}

扩展ExceptionClass {
void m()throws RuntimeException {}
}

但这里没有错误..我以为应该给出相同的错误,因为我上面提到的原因。



我不知道为什么它以这种方式行事。
当我们重写方法时,还要遵循什么规则,在方法签名中抛出异常。

解决方案

NullPointerException RuntimeException 都是未选中的例外。



他们不需要列在 throws 子句中。


I am trying to understand Object Casting and Method Overriding.

I have a piece of code:

    public class ExceptionClass{
        void m() throws SQLException{}

    }

    class A extends ExceptionClass{

        void m() throws Exception{}
    }

This gives an error "Exception Exception is not compatible with throws clause in ExceptionClass.m()".

The same if I write as :

    public class ExceptionClass{
        void m() throws SQLException{}
    }

    class A extends ExceptionClass{

        void m() throws RuntimeException{}
    }

This doesnt give any error and method is also overridden properly. After some analysis I thought that may be, since SQLException extends from Exception class therefore we cant replace "SQLException" with "Exception" in subclass (we are changing the signature of the overridden method).

But then I did this:

    public class ExceptionClass{
        void m() throws NullPointerException{}
    }

    class A extends ExceptionClass{
        void m() throws RuntimeException{}  
    }

But there's no error here..! I thought it should give the same error because of the reason I mentioned above.

I am not sure why it is behaving in this way. Also what are the rules to follow when we override methods, which throw Exceptions in method signature.

解决方案

NullPointerException and RuntimeException are both unchecked exceptions.

They don't need to be listed in the throws clause.

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

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