Search code examples
javaexceptionchecked-exceptions

Why we need to handle or throw checked exceptions in Java?


I am new to Java, I read that checked exception get raised during compile time only i.e. program will not compile successfully if there is a checked exception which is not handled or thrown. If something is preventing a compiler to compile a code, then we could just erase it or recode it in another way so that problem doesn't exist.

For example, if we are trying to open a file which is not there in system, we should not just open it. So why the need to handle/throw these exceptions ?


Solution

  • Your conceptual problem here is that you are conflating what happens at compile time and what happens at runtime; i.e. when the program is compiled by the programmer and when it is run by the user.

    At compile time the compiler analyses the program to determine what exceptions could be thrown. For example

    public static void main(String[] args) {
        FileInputStream fis = new FileInputStream(args[0]);  // HERE
    }
    

    The FileInputStream(String) constructor is declared as throws IOException. (Look it up.) So the compiler knows that the statement at HERE could throw an IOException. And IOException is a checked exception. (Look it up.)

    It doesn't know that it will. It cannot possibly know that it will ... because it doesn't know what args[0] will contain. That is only known at runtime; i.e. when the program is run and the user supplies some command line arguments.

    Q: What does checked exception mean here?

    Well it means the main method either has to be declared as (for example) throws IOException, or it must catch it in a try-catch statement.

    Q: So why is is a checked exception?

    Because it was declared that way!

    Q: Why was it declared that way?

    To force the programmer to do deal with the possibility that the file being opened does not exist, is not readable, and so on. When the program is (eventually) run.

    The compiler is saying "do something about this thing that might happen ...".


    Just to reiterate. The compiler cannot check that the file exists because it doesn't know what pathname the user is going to provide. And even if it did know, AND it checked1 that the file existed at compile, it couldn't know if the file was going to still exist at runtime, possibly on a completely different machine on a different network ... many years in the future.

    1 - This is hypothetical. It doesn't check. It would be pointless.