Exception handling Keywords

Author: Ravi Poswal

It provides the five keywords for exception handling.

  1. Try

  2. Catch

  3. Throw

  4. Throws

  5. Finally

 

TRY: – The try keyword allows you to define a block of code to be tested for errors when executing. A try block cannot be individual work. It is associated with a catch or, finally, block.

Syntax:

try  {

                       statement

                                      }

                     catch(Exception e)

                                 {

                                  Error handling Statement

                                          }

CATCH:- it is associated with a try block. This block cannot separate work. It is used for handling the exception. A single program can be multiple catches block but only try one block.

THROW:- This keyword is used for creating the custom error. 

Syntax: –  

throw (Exception obj);

  • It can throw exceptions that the user has defined.
  • It is also used for re-throwing an exception.
  • It can be used for customized messages for a predefined exception.

Code Example

 class Divide     
  { 
    public static void main(String arg[])
       { 
          try
          { 
               if(arg.length<2) throw(new Exception ("Two arguments must be provided"));
            int x= Integer.parseInt(arg[0]); 
            int y= Integer.parseInt(arg[1]); 
               if(y==0) throw(new Exception("Second no. must be non Zero"));  
                       int z= x/y; 
                 System.out.println("Result is :"+z); 
                         }
         catch (Exception e)//generalized exception handler 
          {
                 System.out.println(e); // general exception
           } 
        }
  } 

FAQs

Yes, we can handle different exceptions separately.

This keyword is used for creating the custom error.
• It can throw exceptions that the user has defined.
• It is also used for re-throwing an exception.
• It can be used for customized messages for a predefined exception.