throws keyword is used in method declaration. It specifies that an exception may be thrown by a particular method.
When should it be used?
If you are catching an exception in your method then you do not need a
throws keyword. For example, if you have a
try/catch within your method then the keyword
throws when defining the method is not necessary. But if there is no
try/catch block and the exception is a checked exception (explained further down) then
throws in the method definition is necessary.
These are exceptions that are checked during compile time. If the code within a method throws a checked exception then the method must either handle the exception or must specify the exception using
These are exceptions that are not checked at compile time.
From the Java documentation “The Throwable class is the superclass of all errors and exceptions in the Java Language”. However you don’t need to specify
throws for all subclasses of Throwable. Any exception that is a subclass of Error or RuntimeException are not checked at compiled time - meaning they are unchecked exceptions. All other exceptions are checked exceptions.
Subscribe via RSS