throws keyword

throws

  • 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 is used in the method’s declaration.
  • A throws clause lists the types of exceptions that a method might throw separated by commas
  • This list should not contain exceptions of type Error or runtime exceptions
    type method-name(parameter-list) throws exception-list{
    // body of method
    }
Example
import java.io.IOException;
class test
{
void demo()throws IOException
{
throw new IOException(“device error”);
}
void sample()throws IOException
{
demo();
}
void accept()
{
try
{
sample();
}
catch(Exception e)
{
System.out.println(“exception handled”);
}
}
public static void main(String args[])
{
test obj=new test();
obj.accept();
System.out.println(“normal flow…”);
}
}

Output:
exception handled
normal flow…


What is difference between throws and throw?

throws is used when the programmer does not want to handle exception and throw it out of a method. throw is used when the programmer wants to throw an exception explicitly and wants to handle it using catch block. Hence, throws and throw are contradictory.


 

Leave a Reply

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