Home >Java >javaTutorial >Can Overridden Java Methods Throw Broader Checked Exceptions Than Their Parent Methods?

Can Overridden Java Methods Throw Broader Checked Exceptions Than Their Parent Methods?

Susan Sarandon
Susan SarandonOriginal
2024-12-01 22:26:12227browse

Can Overridden Java Methods Throw Broader Checked Exceptions Than Their Parent Methods?

Throwing Exceptions in Overridden Methods

In Java, overriding methods inherit the exceptions declared by their parent methods. However, there are certain restrictions on the types of exceptions that can be thrown by overriding methods.

Specifically, the overriding method cannot throw checked exceptions that are broader or new compared to those declared by the overridden method. This means that if a method declares to throw a particular exception, the overriding method can only throw that exception or its subclasses.

Reasoning

This restriction helps maintain the Liskov Substitution Principle, which states that objects of a subclass should be able to replace objects of the parent class without disrupting the behavior of the program. If the overriding method could throw a broader exception than the overridden method, it would violate this principle and could lead to unexpected behavior.

Example

Consider the following code:

class A {
  public void foo() throws IOException {
    ...
  }
}

class B extends A {
  @Override
  public void foo() throws SocketException {
    ...
  }
}

In this example, the foo() method in class A declares to throw an IOException. The overriding method in class B throws a SocketException, which is a subclass of IOException. This is allowed.

However, if the foo() method in class B were to throw an SQLException, which is not related to IOException, it would not be allowed. This would violate the rule that the overriding method cannot throw broader exceptions than the overridden method.

Implications

This rule impacts the design of overridden methods, as it limits the exceptions that can be thrown by the overriding method. Developers must carefully consider the exceptions declared by the overridden method when overriding it to avoid compiler errors and runtime exceptions.

The above is the detailed content of Can Overridden Java Methods Throw Broader Checked Exceptions Than Their Parent Methods?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn