+ 2
What is the difference between throw and throws keyword in java?
4 Respuestas
+ 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();
} } }
+ 4
The question may have been asked before. Please search.
+ 3
Thanks zemiak
+ 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 ~