0

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
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
Switchkick
  • 2,716
  • 6
  • 21
  • 28

6 Answers6

8

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

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.
NPE
  • 486,780
  • 108
  • 951
  • 1,012
3

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

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
2

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

try {
    fallingBlocks();
} catch (FileNotFoundException e) {
    /* handle */
}
home
  • 12,468
  • 5
  • 46
  • 54
2

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
}
Harry Joy
  • 58,650
  • 30
  • 162
  • 207
2

You call it like any other method too. However the method might fail. In this case the method throws the exception. This exception should be caught with a try-catch statement as it interrupts your program flow.

Xeno Lupus
  • 1,504
  • 3
  • 12
  • 17