Difference between throw and throws Keyword for Exception Handling in java
Both keywords are used in exception handling which handles run-time errors and compile-time errors.
Consider an example
public static void main(String args[]) throws IOException, SQLException{void sum() throws ArithmaticException{
//////// Code///////
}
void divide(){
try{
throw new ArithmeticException(" Something went wrong!!!!");
} catch (Exception exp){
System.out.println(" Error: "+exp.getmessage() );
}
}
}
void divide(){
try{
throw new ArithmeticException(" Something went wrong!!!!");
} catch (Exception exp){
System.out.println(" Error: "+exp.getmessage() );
}
}
}
Difference between throw and throws
1. The throw keyword used to handle the exception in the inside block of the program like try-catch block
but throws are also keyword which lies outside the block
2. throw handle single exception at the run time but it can throw any exception type like an
arithmetic exception, numeric exception, SQL exception, etc
but where throws handle one or more exceptions.
3. It should be lies inside the block(function) inside the try block(which check the exception)
but we should always mention the kind of exception in adjacent to throws keyword.
4. Checked exceptions( IOException, SQLException) can be propagated using throws only and we handle in compile time.
but Checked exception cannot be propagated using throw only.