Calling a method which throws FileNotFoundException

30,310

Solution 1

You call it, and either declare that your method throws it too, or catch it:

public void foo() throws FileNotFoundException // Or e.g. throws IOException
{
    // Do stuff
    fallingBlocks();
}

Or:

public void foo()
{
    // Do stuff
    try
    {
        fallingBlocks();
    }
    catch (FileNotFoundException e)
    {
        // Handle the exception
    }
}

See section 11.2 of the Java Language Specification or the Java Tutorial on Exceptions for more details.

Solution 2

You just call it as you would call any other method, and make sure that you either

  1. catch and handle FileNotFoundException in the calling method;
  2. make sure that the calling method has FileNotFoundException or a superclass thereof on its throws list.

Solution 3

You simply catch the Exception or rethrow it. Read about exceptions.

Solution 4

Not sure if I get your question, just call the method:

try {
    fallingBlocks();
} catch (FileNotFoundException e) {
    /* handle */
}

Solution 5

Isn't it like calling a normal method. The only difference is you have to handle the exception either by surrounding it in try..catch or by throwing the same exception from the caller method.

try {
    // --- some logic
    fallingBlocks();
    // --- some other logic
} catch (FileNotFoundException e) {
    // --- exception handling
}

or

public void myMethod() throws FileNotFoundException {
    // --- some logic
    fallingBlocks();
    // --- some other logic
}
Share:
30,310
Switchkick
Author by

Switchkick

Updated on September 28, 2020

Comments

  • Switchkick
    Switchkick over 3 years

    I'm pretty sure this is an easy one but I could not find a straight forward answer. How do I call a method with a throws FileNotFoundException?

    Here's my method:

    private static void fallingBlocks() throws FileNotFoundException
    
  • Madhu Avinash
    Madhu Avinash almost 7 years
    Hi Jon Skeet, Is there any other way through which i can achieve the same ?
  • Jon Skeet
    Jon Skeet almost 7 years
    @MadhuAvinash: No, you either have to catch the exception or declare that your method might throw it. That's just the way it is.