Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Rule #1:
* If the super-class overridden method does not throw an exception,
* subclass overriding method can only throws the unchecked exception,
* throwing checked exception will lead to compile-time error.
*
* Rule #2:
* If the super-class overridden method does throws an exception, subclass
* overriding method can only throw same, subclass exception. Throwing parent
* exception in Exception hierarchy will lead to compile time error. Also there
* is no issue if subclass overridden method is not throwing any exception.
*
*/
class ParentClass {
void method1 () {
System.out.println("parent method1");
}
void method2 () {
System.out.println("parent method1");
}
void method3 () throws RuntimeException{
System.out.println("parent method3");
}
}
class ChildClass {
@Override
void method1 () throws ArithmeticException{
System.out.println("child method1");
}
// Throwing checked exception will give compilation error
// @Override
// void method2 () throws Exception
// System.out.println("child method2");
// }
/**
* This method can throw the same exception (RunTimeException), can throw subclass of
* the parent thrown exception like (ArithmaticException), can throw no exceptions but
* it can't throw parent of RunTimeException (Here) in exception hierarchy (e.g. Exception).
* This will give compilation error.
*/
@Override
void method3 () {
System.out.println("child method3");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment