+ 9
Throw and Throws in java
How throw and throws keyword works during exception handling in java. Can anyone explain it with an example..
4 Respuestas
+ 5
Here is a decent write up
https://www.geeksforgeeks.org/throw-throws-java/
+ 7
Throws clause is used to declare an exception, which means it works similar to the try-catch block. On the other hand throw keyword is used to throw an exception explicitly.
If we see syntax wise than throw is followed by an instance of Exception class and throws is followed by exception class names.
+ 7
When you define a method with a potential exception you declare throws YourException. When some condition is not met you throw YourException. For example
Class Example{
public double div(int arg1, int arg2) throws ArithmeticException{
If(arg2 == 0){
throw new ArithmeticException ();
}else{
return arg1/ arg2
}
}
Now the user of the method has to catch the exception. For example:
Example example = new Example();
try{
double result = example.div(42, 2);
}catch(ArithmeticException e){
e.printStackTrace();
}
+ 4
throw is used to explicitly throw an exception to catch block or if there is no catch block the program will halt.
It is used inside the method body
throws keyword is used for just telling the programmer, the method might throw an exception so do not forget to handle it.
It is used with method signature
void a()throws ArithmeticException
{
throw new ArithmeticException("error");
}