+ 9

Throw and Throws in java

How throw and throws keyword works during exception handling in java. Can anyone explain it with an example..

24th Jun 2019, 2:11 AM
Prakash Joshi
Prakash Joshi - avatar
4 odpowiedzi
24th Jun 2019, 3:00 AM
John Wells
John Wells - avatar
+ 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.
24th Jun 2019, 3:50 PM
KEERTHANA PEDDAPYATA
KEERTHANA PEDDAPYATA - avatar
+ 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(); }
25th Jun 2019, 4:18 AM
Dan Rhamba
Dan Rhamba - avatar
+ 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");  }
24th Jun 2019, 3:02 AM
kiRA
kiRA - avatar