Skip to main content

throws keyword


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

Popular posts from this blog

Core Java

Content 1 - Language fundamental   Identifier Reserved words Data types Literals Arrays Types of variables Var arg method Main method Java coding standards 2 -  Declaration and Access Modifiers Java source file structure Class modifiers Member modifiers Interfaces 3 - Exception Handling Introduction Runtime stack mechanism Default exception handling in java Exception hierarchy Customized exception handling by try-catch  Control flow in try-catch Methods to print exception information Try with multiple catch blocks Finally Difference between final, finally, finalize Control flow in try-catch-finally Control flow in nested try-catch-finally Various possible combinations of try-catch-finally throw keyword throws keyword Exception handling keywords summary Various possible compile-time errors in exception handling Customized exceptions Top-10 exceptions  4 - String Concept of String Immutable String String Compa...