JAVA- Specifying the exceptions

We use two keywords to specify the exception these are:

  1. throw
  2. throws

1.      throw: All methods use throw statement to throw an exception. The throw statement requires a single arguments i.e. a Throwable object. Throwable objects are instance of any sub class of the Throwable class. Followings are the example of throw statement:

 e.g.                 

class ThrowTest

{

static void test(object e)

{

System.out.println(e.tostring());

}

static void MyThrow()

{

try

{

throw new NullPointerException(“this is demo”);

}

catch(NullPointerException e)

{

System.out.println(“Inside MyThrow”);

}

}

}

public static void main(string args[])

{

try

{

test(null);

}

catch(NullPointerException e)

{

MyThrow();

}

}

 

2.      throws: The throws keyword is use with the method at throws exception this is necessary for all exceptions expect those of type “Error” or “Run Time Exception” or any of their sub classes.

Syntax:

data-type  method-name(parameter list) throws exception-list

{

//body of the method

}

e.g.     

public void PasswordCheck()throws SecurityException

{

throws(new SecurityException(“Invalid password”));

}

 Program:

//PROGRAM TO IMPLEMENT EXCEPTION HANDLING USING TRY AND CATCH BLOCKS

class arithExcep

{

public static void main(String agrs[ ])

{

int a=10,b=0 ;

try

{

a=a/b;    // 10/0

System.out.println(“Don’t print”);

}

catch(ArithmeticException ae)

{

System.out.println(“Divide by zero”);

System.out.println(“Change the value of b”);

}

System.out.println(“Quit”);

}

}

Leave a Reply

Your email address will not be published. Required fields are marked *