exception handling

Exception handling:-
Exception is an abnormal condition that occurs in a program at runtime.
Generally it terminates the program. Few conditions that raises an exception are divide by zero, file not found, number format exception, array out of bound exception

try block
It is used to write the code, which might throw an exception. There can be any number of try blocks in a program.

catch block:-
It is used to write the statements which are supposed to be executed if an exception is thrown. One try block can have more than one catch blocks.
It takes an object of an exception class as an argument

throw keyword:-
It is used to explicitly throw an object of an exception class.

throws keyword:-
It is used to declare that a particular function will not handle any exceptions occurred, and tells the compiler to handle the exceptions on it’s own.
Basically it re throws an exception.

finally block:-
It is used to write the statements that are compulsory to execute even if the exception is thrown or not.
This should be the last block in the code.

The syntax of try catch and finally is :

try {
  // code
} catch (ExceptionType e) { 
  // catch block
}catch (ExceptionType e) { 
  // catch block
}catch (ExceptionType e) { 
  // catch block
} finally {
  // finally block
}

Example code to understand exception handling in java.

Class Exception_Demo
 {
       public static void main()
      { 
          try
          { 
               int a =4, b=0;
               int div=a/b;
               system.out.println(div); 

            }
            catch( ArithmeticException  e) 
           {   
               system.out.println("for divide by zero this will execute"); 
            } 
          catch(Exception e) 
           {   
            system.out.println("for any other exception this will execute"); 
            }
          finally
           {
                system.out.println("In finally"); 
            } 
        }
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here