user3818650
user3818650

Reputation: 571

Java - Needing not needed exception catching or throwing

So in Java for this example, why does the exception need to be thrown, when it never actually happens?

import java.io.*;

public class Files{
    public static void main(String[] args) throws IOException //Why does exception need to be thrown
    {
        FileOutputStream os = new FileOutputStream("myfile");
        os.close();
    }

Why does Java require this?

Upvotes: 1

Views: 58

Answers (4)

Vishal Bansod
Vishal Bansod

Reputation: 61

Both lines below throw a checked exception and as per Java it must be either handled or must be declared so that callers can decide what should be done.

FileOutputStream os = new FileOutputStream("myfile");
os.close();

In this case the first line throws FileNotFoundException where as later throws IOException. As IOException is a parent of FileNotFoundException, we have option to declare just IOException.

Upvotes: 3

gutte
gutte

Reputation: 1473

the constructor

FileOutputStream("myfile");

throws FileNotFoundException which extends IOException. so you can throw IOException or FileNotFoundException and it is the same thing. you can also throw Exception for the same reason

Upvotes: 1

TheLostMind
TheLostMind

Reputation: 36304

If you check the oracle docs for FileOutputStream, you can see this :

Throws: FileNotFoundException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason SecurityException - if a security manager exists and its checkWrite method denies write access to the file.

This is for the call to the constructor FileOutputStream os = new FileOutputStream("myfile");. So, this is why the compiler asks you to explicitly check for (handle) IOException.

The same applies to close() method.

Upvotes: 2

Marv
Marv

Reputation: 3557

It needs to throw it because new FileOutputStream() can throw this exception. See Specifying the Exceptions Thrown by a Method. Alternatively instead of having the method throw the exception, you could also surround with try...catch:

try {
    FileOutputStream os = new FileOutputStream("myfile");
    os.close();
catch (IOException e) {
    e.printStackTrace();
}

Upvotes: 3

Related Questions