When should we use throws keyword in Java?
- It is all about how to recover from an exception. What should e.g.
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 case - Of course you can handle exceptions in your module if its clear how said exceptions should be handled. If the handling is dependent on the callee or context, let the calling function decide
- Should be clear by now
Let 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
:
- If the file path comes from user input, you might ask the user to enter another file path
- You might display an error message
- You might not do anything and just let it crash
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.