-1

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 ?

wholesome
  • 57
  • 9
  • Since the syntax of Java is such that if it is defined that a function throws an Exception, you must either handle the Exception or also make your function throw a Checked Exception using the `throws` keyword in function signature so that it is handled by JVM when thrown. But remember that Exception in Java is always handled, either its you that is handling it or the JVM(which shall crash the program & is generally a bad practice which is why we have checked Exception) – humble_barnacle Feb 01 '22 at 07:24
  • In a perfect world where everyone only writes correct code, then we would not need exceptions, but we don't write perfect code so checked exceptions are a great way to easily pick up the most common and obvious errors that would quite likely crash your application at some point in time. Also, in response to "we should not just open it" what should your code do in a situation where your code depends on a file to function? – sorifiend Feb 01 '22 at 07:24
  • 1
    *"In a perfect world where everyone only writes correct code ..."* and user's don't give incorrect pathnames for files, etc. – Stephen C Feb 01 '22 at 07:25
  • @StephenC if there is incorrect pathnames to files, the compiler prompts that and we can correct it in the code itself. – wholesome Feb 01 '22 at 07:28
  • 1
    ".... and user's don't give incorrect pathnames for files, etc" and the pathname works across all platforms – humble_barnacle Feb 01 '22 at 07:29
  • 1
    And what happens if the file disappears between checking the pathname and actually loading it, or while reading it, for example, if a USB drive containing the file is unplugged? A checked exception solves this issue and lets us define how our code should behave. – sorifiend Feb 01 '22 at 07:31
  • 2
    @soumyadip_poddar - Really? Really? The compiler can check that the pathname that a user supplies as a command line argument is correct. The pathname is not known at compile time. – Stephen C Feb 01 '22 at 07:31
  • @StephenC No, not the correct pathname, but the file is not present in the given pathname. – wholesome Feb 01 '22 at 07:33
  • @sorifiend Yes this example sounds relatable to me. Thankyou. – wholesome Feb 01 '22 at 07:34
  • I don't understand the distinction that you are making. – Stephen C Feb 01 '22 at 07:34
  • @StephenC I am using eclipse if I am giving a file name which is not present in the desired location then, the program itself will not compile. I am not saying that compiler will say the pathname where the file actually is, but it will say that the file is not present where it is checking. – wholesome Feb 01 '22 at 07:35
  • 2
    A FileNotFoundException is thrown **at runtime** which the program attempts to open a file. At compile time, the compiler probably doesn't even know what the pathname is. So how can it check it? (And even if it did know, it **doesn't** check it. The compiler doesn't attempt to open the file. It wouldn't be a useful thing to do. The user may not have created it yet.) – Stephen C Feb 01 '22 at 07:38

3 Answers3

6

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Yes I was going through more resources and I realized that my understanding was not correct. In compile time it shows which exceptions could be thrown and in runtime if the exception occurs it get thrown and if it doesn't occur it doesn't get throwed. Thankyou it answered my question. – wholesome Feb 01 '22 at 07:59
3

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.

ktul
  • 183
  • 9
0

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

humble_barnacle
  • 460
  • 1
  • 4
  • 19
Mario Santini
  • 2,905
  • 2
  • 20
  • 27
  • Can you explain your second sentence-" But the exception itselfs will not be raised until runtime, when the case appened. " because checked exceptions are evaluated in compile time only. – wholesome Feb 01 '22 at 07:31
  • @soumyadip_poddar Exceptions are raised only during runtime but compiler only knows about Checked exceptions so it tells you to either handle it or bubble it upwards to the caller – humble_barnacle Feb 01 '22 at 07:33
  • 1
    The only thing that happened in compile time, is that the compile will check if you handle the checked exceptions. But no exception will be raised in compile time, as your code is not running. – Mario Santini Feb 01 '22 at 07:35
  • "But the exception itselfs will not be raised until runtime, when the case appened." is a typo, it meant to be read as "But the exception itself will not be raised until runtime, in case it happens." – humble_barnacle Feb 01 '22 at 07:35
  • @humble_barnacle is right, I just wrote it badly. – Mario Santini Feb 01 '22 at 07:37
  • Actually I meant to say that if the compiler sees that I didn't handle/throw the checked exceptions then it will not compile. So in that case we can just rewrite the code which is causing the exception rather than handling or throwing it. – wholesome Feb 01 '22 at 07:39
  • You are almost there. It is not the code that is "causing" the exception, rather it is the code that can raise an exception. That don't mean it will do the exception at runtime, just that can be the case. And to avoid the program to crash, in that case, you should handle the exception. – Mario Santini Feb 01 '22 at 07:42
  • 1
    @soumyadip_poddar If you are using built-in Java IO/File methods, then you will always have checked exceptions because the writers of the language know just how common these errors are. You could use other libraries that hide/suppress the checked exceptions, or you could dig deep and override it to remove them, but at its core you will still have a problem that will quite likely crash your application, and most coders don't have the knowledge to do it correctly without an absolute mess of code. I prefer writing two lines of checked exceptions, then hundreds of lines to work around them. – sorifiend Feb 01 '22 at 07:44
  • @soumyadip_poddar methods like mentioned here https://docs.oracle.com/javase/7/docs/api/java/io/File.html#method_summary – humble_barnacle Feb 01 '22 at 08:13
  • @MarioSantini Yes thankyou. I understood. – wholesome Feb 01 '22 at 08:36