+ 1
what is different btween throw and try catch in java
3 Respuestas
+ 8
If an Exception occurs inside try block, catch block is executed. The throw keyword is used to throw an exception explicitly.
+ 5
throw is used when you want to force a system to give an exception.
catch is used when you want the system to do something when an exception occurs.
Additional Information : Functions can also be made to return an exception too!
+ 3
Try block contains the code which you think may throw the exception.. so in this block the exception occurs.
catch block as name suggests will catch the exception thrown by try block.
Now its your choice to handle the exception or throw it to other handlers using throw keyword.
so the pupose of each keyword is different in this manner,
Example:
try
{
int a = 5;
int b = 0;
int c = a / b;
}catch(ArithmaticException ex)
{
throw new InvalidNumberException("Invalid Number",ex);
}
so in the code above it will throw ArithmaticException and will catch by the catch block and again it will be throw from catch block.
Hope it helps;
Happy Programming😃