Monday 14 November 2016

throwand throws:



throw:
   In Java, it is possible for a program to throw an exception explicitly, using throw statement.
The general form of throw is:
throwThrowableInstance;
ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
The flow of execution stops immediately after the throwstatement; any subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of exception. If it does find a match, control is transferred to that statement. If not, then the next enclosing trystatement is inspected, and so on. If no matching catch is found, then the default exception handler halts the program and prints the stack trace. 
 Example:
classThrowcheck
{
public void generate()
 {
try
   {
throw new ArrayIndexOutOfBoundsException();
   }
catch(ArrayIndexOutOfBoundsException e)
   {
System.out.println("Exception occurred inside function");
throw e;
   }
 }
}
class Throw
{
public static void main(String args[])
 {
try
  {
Throwcheck t=new Throwcheck();
t.generate();   
  }
catch(ArrayIndexOutOfBoundsException e)
  {
System.out.println("Exception occurred inside main");
  }
 }
}
Output:
Exception occurred inside function
Exception occurred inside main
throws:
In Java, if a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. 
 A throws clause lists the types of exceptions that a method might throw. 
 This is necessary for all exceptions, except those of type Error or Runtime Exception, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile time error may result.
        The general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
//body of method.
}
Here exception-list is a comma-separated list of the exceptions that a method can throw.
     Example:
classThrowcheck
{
public void generate() throws ArrayIndexOutOfBoundsException
 {
System.out.println("Inside the function");
throw new ArrayIndexOutOfBoundsException();
 }
}
class Throws
{
public static void main(String args[])
 {
try
  {
Throwcheck t=new Throwcheck();
t.generate();   
  }
catch(ArrayIndexOutOfBoundsException e)
  {
System.out.println("Exception occurred inside main");
  }
 }
}
Output:
Inside the function
Exception occurred inside main

No comments:
Write comments