class A{
}
class B extends A throws Exception{
}
Above Code gives CompileTime Error "Syntax error on token "throws", implements expected"
Can anyone tell me the exact reason why this is not permissible in java. Thanks in advance
class A{
}
class B extends A throws Exception{
}
Above Code gives CompileTime Error "Syntax error on token "throws", implements expected"
Can anyone tell me the exact reason why this is not permissible in java. Thanks in advance
A class is only a template for an object. While it does contain methods that actually execute instructions, it cannot itself throw an exception because it doesn't execute actual code. The throws clause therefore can only be used on methods, not the class itself.
As a general rule when you override a method you cannot throw checked Exceptions which are not already been defined by the method in parent class/interface. This is to make sure checked exceptions are handled , if not you get compile-time error.
If there is code where the method is called using parent reference , then at compile time the overridden implementation is not known and so is the exceptions thrown by it so compiler would not be able to put error for unhandled checked exception. To avoid that, compiler doesn't allow to define new checked exceptions for overriden method.