Site icon Narayana Tutorial

throw,throws,finally

Classes and Objects interview questions

We are going to explaining What is throw,throws,finally in java?

throws

Syntax

public void  getData() throws FileNotFoundException{
//To do something
}

Syntax

public void  getData() throws IOException, FileNotFoundException, SQLException {
   //To do something
}

throw

Syntax

public void  getData(){
try {
  throw new Exception("Exception occured.");
} catch (Exception exp) {
  System.out.println("Error: "+exp.getMessage());
}
}

Syntax

throw new ArithmeticException("An integer should not be divided by zero!!")
throw new IOException("Connection failed!!")

Finally

Syntax

Combination 1

try{
//To do something
}finally{
//To do something
}
Combination 2

try{
//To do something
}catch(Exception e){
//To do something
}finally{
//To do something
}
Combination 3
try{
//To do something
}catch(ExceptionType1 e1){
//To do something
}catch(ExceptionType2 e2){
//To do something
}catch(ExceptionType3 e3){
//To do something
}finally{
//To do somehting
}