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

1.2k views Asked by At

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 ?

3

There are 3 answers

1
Stephen C On BEST ANSWER

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.

10
Mario Santini On

Checked exception in Java have to be handled, that is why the compiler will complain about and didn't compile the code.

But the exception itselfs will not be raised until runtime, in case it happens.

When you write your code you should just handle properly all your checked exception, so you have to write a try catch block or just return the exception from the method.

If you use some library that raises checked exception you can just handle in one of the 2 ways I have already explained.

But in your code you can choose to use unchecked exceptions.

Those kind of exceptions can be ignored and the compiler will be just fine. Of course your app will crash if one of those unchecked exception is raised while execution and it is not caught.

But that can be desirable in certain situation, where there is no right way to handle the Exception and it is generally a subclass of Error.

Anyway you should not think about on how to handle the error cases in your code but only Exceptions.

More: Exception class, Error class

0
ktul On

You shouldn't see exception handling as a problem but as a feature.

Assume exceptions wouldn't exist.

var file = new File("test.txt");
if (!file.exists()) {
    file.createNewFile();
}
var writer = new FileWriter(file);
// ...

What could go wrong?

  • Between the check whether the file exists and opening the reader, the file might have been removed by another thread/process. So even though you created it, it's gone -> you need to somehow lock the file
  • Your memory is full, hence the file could not be created -> you need to check the result of createNewFile for that.
  • The file exists, but is a directory.
  • The file is locked, because another process is writing to it -> You need to check if it is being written to.

This would do it (still assuming no exceptions):

var file = new File("test.txt");
if (!file.exists()) {
    if(file.createNewFile()) {
        if (!file.isDirectory()) {
            if (!isUsed(file)) {
                var writer = new FileWriter(file);
                // ...
            }
        }
    }
}

This is a lot of code and still doesn't handle the first problem.

Whereas

var file = new File("test.txt");
try {
    var writer = new Filewriter(file);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

is way shorter, clearer, easier to understand.

Also, usually, it is more likely that everything works as supposed that that any of these problems occur. So instead of assuming all the worst and doing multiple checks beforehand, one just assumes the best and if something fails, you look for the reason.

This also impacts the runtime. If you run the no-exception code 1000 times, all these checks will be run a 1000 times, no matter if they fail or not. For the exception-code this is not the case, the might never be run at all.