Throws statement
In our program, if there is any chance of raising checked exception compulsory we should handle either by try-catch or by throws keyword otherwise the code won’t compile.
Example:
class Test3
{
public static void main(String[] args){
Thread.sleep(5000);
}
}
• Unreported exception java.lang.InterruptedException; must be caught or declared to be thrown. We can handle this compile-time error by using the following 2 ways.
Example:
• Hence the main objective of the “throws” keyword is too delicate the responsibility of exception handling to the caller method.
• “throws” keyword required only checked exceptions. Usage of throws for unchecked exceptions there is no use.
• “throws” keyword required only to convenes complier. The usage of throws keyword doesn’t prevent abnormal termination of the program.
Example:
class Test
{
public static void main(String[] args)throws InterruptedException{
doStuff();
}
public static void doStuff()throws InterruptedException{
doMoreStuff();
}
public static void doMoreStuff()throws InterruptedException{
Thread.sleep(5000);
}
}
Output:
Compile and running successfully.
• In the above program if we are removing at least one throws keyword then the program
won’t compile.
Case 1: we can use throws keyword only for Throwable types otherwise we will get a compile-time error saying incompatible types.
Example:
Case 2:
Example:
Case 3:
• In our program, if there is no chance of raising an exception then we can’t right catch block for that exception otherwise, we will get a compile-time error saying exception XXX is never thrown in the body of the corresponding try statement. But this rule is applicable only for fully checked exceptions.
Example:
Comments
Post a Comment