简体   繁体   English

Java抛出异常的方法覆盖

[英]Method overriding in Java throwing exceptions

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()". 这给出了一个错误“异常异常与ExceptionClass.m()中的throws子句不兼容”。

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). 经过一些分析我认为可能是,因为SQLException从Exception类扩展,因此我们不能在子类中用“Exception”替换“SQLException”(我们正在改变重写方法的签名)。

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. NullPointerExceptionRuntimeException都是未经检查的异常。

They don't need to be listed in the throws clause. 它们不需要在throws子句中列出。

You can only reduce or eliminate the exception thrown in your overridden methods. 您只能减少或消除重写方法中抛出的异常。 Throwing broader exceptions is not allowed by the language. 语言不允许抛出更广泛的异常。

From the Java docs : 来自Java文档

"The throws clause of an overriding method may not specify that this method will result in throwing any checked exception which the overridden method is not permitted, by its throws clause, to throw." “重写方法的throws子句可能没有指定此方法将导致抛出任何被抛出的方法不允许被覆盖的方法被抛出的任何已检查异常。”

Yes, you are right that the first problem happened because of change of method signature. 是的,你是正确的,因为方法签名的变化发生了第一个问题。 Using NPE and RuntimeException to whet it further is not correct because runtime exceptions need not be declared on the signature. 使用NPE和RuntimeException进一步激活它是不正确的,因为不需要在签名上声明运行时异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM