0
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

shrishti
  • 95
  • 5
  • 9
    Methods throw exceptions, not classes. – rgettman Apr 30 '18 at 18:20
  • 2
    Throws can *never* be used on a class, so you can't use throws and extends together either. – Andy Turner Apr 30 '18 at 18:23
  • @AndyTurner Actually I got confused. I was trying to apply throws to run() method of a custom Thread class but I was getting error "Exception InterruptedException is not compatible with throws clause in Thread.run() " . Can you tell me why? – shrishti Apr 30 '18 at 18:32
  • @shrishti because it's a checked exception, and the method does not declare that it throws any checked exceptions. – Andy Turner Apr 30 '18 at 18:47

2 Answers2

4

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.

Martin
  • 1,977
  • 5
  • 30
  • 67
  • Could you tell me why "throws Exception" does not work with run method of a custom thread class? – shrishti Apr 30 '18 at 18:33
  • 1
    https://stackoverflow.com/questions/4491606/java-thread-run-method-cannot-throw-checked-exception – Martin Apr 30 '18 at 18:39
0

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.

dev. K
  • 63
  • 1
  • 6