Wednesday 20 November 2019

exception - When should we use throws keyword in Java?




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:




  1. Why don't we use try catch block inside the module to handle the checked exceptions?

  2. Can we handle checked exceptions inside the module using try-catch block?

  3. If answer of (2) is YES, then Why we are forcing the caller to except those exceptions using throws keyword, when we could except the same inside the module itself?




In that way we need not to manually except the exceptions every time the method is called.


Answer



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 a FileNotFoundException, 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.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...