throws keyword is used only for checked exception. It instructs the caller to use try catch block to except all the listed exceptions by throws keyword.
Since we know what kind of checked exception might occur in our module, then:
In that way we need not to manually except the exceptions every time the method is called.
The throws keyword in Java is used to declare exceptions that can occur during the execution of a program. For any method that can throw exceptions, it is mandatory to use the throws keyword to list the exceptions that can be thrown.
The throws keyword indicates what exception type may be thrown by a method. There are many exception types available in Java: ArithmeticException , ClassNotFoundException , ArrayIndexOutOfBoundsException , SecurityException , etc. Syntax: throw is followed by an object (new type)
The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception. So, it is better for the programmer to provide the exception handling code so that the normal flow of the program can be maintained.
Answer: The “throws” keyword is used to declare the exception with the method signature. The throw keyword is used to explicitly throw the exception. The try-catch block is used to handle the exceptions thrown by others.
java.lang.File
do when the file does not exist? As it doesn't know what would be the best for the callee, it lets the callee handle this caseLet me use FileInputStream::new
throwing FileNotFoundException
as an example to clear up your misunderstanding.
So for example we have some code like this:
FileInputStream fis = new FileInputStream("/some/path/to/file.txt");
That might throw a FileNotFoundException
, and you are saying that,
FileInputStream
obviously knows that it is going to throw aFileNotFoundException
, so why does it not handle it itself?
Because FileInputStream
does not know how to handle the exception!
Depending on the situation, there are lots of ways to handle a FileNotFoundException
:
All of the above could be completely sensible options depending on the situation. How is a FileInputStream
going to know about your situation? It's not!
That's why it's saying, with a throws
clause:
I'm throwing these exceptions, handle it yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With