+ 2

What is the difference between throw and throws keyword in java?

22nd Aug 2019, 7:12 AM
Piyush Srivastava
Piyush Srivastava - avatar
4 Respostas
+ 2
it is about Exceptions, - if you want execute exception from your code use 'throw': throw new UnsupportedOperationException(); program ends with error, or in other places of code you can catch this thrown exception with try-catch command - if your method can throw 'checked exception' and you not want to catch it, you must inform about it in the head of your method with 'throws' keyword. Then this exception must be caught by someone who calls your method. 'Checked exceptions' are exceptions which must be compulsorily caught. import java.io.FileNotFoundException; public class Program { public static void main(String[] args) { try { // uncomment one of lines myMethod(1); // File not found // myMethod(11); // Exception in thread "main" .. } catch (FileNotFoundException e) { System.out.println("File not found"); } } static void myMethod(int format) throws FileNotFoundException { switch (format) { case 1: // ... throw new FileNotFoundException(); // checked exception //case 2: ... default: throw new UnsupportedOperationException(); } } }
22nd Aug 2019, 6:09 PM
zemiak
+ 4
The question may have been asked before. Please search.
22nd Aug 2019, 8:55 AM
Sonic
Sonic - avatar
+ 3
Thanks zemiak
22nd Aug 2019, 6:43 PM
Piyush Srivastava
Piyush Srivastava - avatar
+ 2
You can see this link, there provide good explaination https://beginnersbook.com/2013/04/difference-between-throw-and-throws-in-java/ Hope it may help you ~
22nd Aug 2019, 7:15 AM
Uchiha Itachi
Uchiha Itachi - avatar