Throwing our Own Exceptions in Java

                         
                    
Throwing our exceptions:

There may be times when we would like to throw our exception we can do this by using the keyword throw as follows.
 
          Throw new throwable subclass;

Ex :  throw new ArithmeticException ( );

         throw new NumberFormatException ( ) ;

Note that exception is a subclass of throw able and therefore myException is a subclass of throw able class. A object of a class that extends throwable can be thrown and caught.

import java .lang. Exception;
class myException (String message)
{
 super  (message);
 }

  class testMyException
  {

  public static void main (String args[ ] )
   {
     int x= 5,  y=100;
          try
          {
           float z =(float) x/(float)y ;
           if(z < 0.01)
           {
            throw new myException (“ number is too small) ;
            }
          }
            catch ( myException e)
           {
            System.out.println (“ caught my exception”);
            System.out.println (e. getMessage ( ) );
            }
            finally
            {
            System.out.println (“ I am always here”);
            }
      }
     }

The object which contains the error message.“Number is too small” is caught by catch block. which then displays the message using the        getMessage ( ) method.                                                                    



Related

Java 2586394748924210460

Post a Comment

emo-but-icon

item