Skip to content

Instantly share code, notes, and snippets.

@Kaushal28
Created July 22, 2019 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kaushal28/3107e25c9f06d7e36eef200a36878d97 to your computer and use it in GitHub Desktop.
Save Kaushal28/3107e25c9f06d7e36eef200a36878d97 to your computer and use it in GitHub Desktop.
/**
* 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