throw vs throws keyword
throw keyword:
throw keyword is used to explicitly throw an exception from a block of code or method of a Java program.
Note: You can throw custom exception, checked and unchecked Exception using throw keyword as
throw new Exception("String message ");
Example:
class Program{
public static int div(int a, int b) throws ArithmeticException{
if(b==0){
throw new ArithmeticException("Cannot divide the number with zero as it will produce infinite ");
}
}
public static void main(String args[]){
try{
int c = Program.div(4, 0)
System.out.println("result is:"+c);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
int d = a+b;
System.out.println("addition is :"+d);
}
}
2. throws keyword:
throws keyword is defined with the method signature indicating that this method might throw some specified exception.
Note: If we do not declare throws with the method which throws some exception then it will lead to a compile time error.
void method(parameters...) throws Exception
Note: The program must handle the exception thrown using try catch block.
Example:
class Program{
public static int div(int a, int b) throws ArithmeticException{
if(b==0){
throw new ArithmeticException("Cannot divide the number with zero as it will produce infinite ");
}
}
public static void main(String args[]){
try{
int c = Program.div(4, 0)
System.out.println("result is:"+c);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
int d = a+b;
System.out.println("addition is :"+d);
}
}
Comments
Post a Comment