freetimestudys@gmail.com          +91-7097633380
  Login Here                        

Throws

1) Throw keyword is used to create exception object explicitly. But the main purpose of the throws keyword is bypassing the generated exception from present method to caller method.
2) Throw keyword is used in the method body. But throws keyword we have to use in the method declaration.
3) It is possible to throws any number of exceptions at a time based on the programmer requirement.
In the java language we are handling the Exception in two ways
1) By using try-catch blocks
2) By using throws keyword

By using try-catch blocks

class Test
{
void studentDetails()
{
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("please enter student name");
String sname=br.readLine();
System.out.println("hi "+sname);
}
catch(IOException e)
{
System.out.println("we are getting Exception"+e);
}
}
public static void main(String[] args)
{
Test s1=new Test();
s1.studentDetails();
}
}

intput and output

output:please enter student name
venkat
hi venkat

By using throws keyword

import java.io.*;
class Test
{
void studentDetails()throws IOException
{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("please enter student name");
String sname=br.readLine();
System.out.println(" hi :"+sname);
}
public static void main(String[] args)throws IOException
{
Test s1=new Test();
s1.studentDetails();
}
}

intput and output

output:please enter student name
venkat
hi venkat