2

I can't remeber how this works. If I have a method that throws an exception I can deal with it in the method or declare that the method throws exception. What happens when I have a method within a method that might throw an exception, but is not explicitly declared that it might?

For example:

public void A() throws Exception
{
  B();
}

public void B()
{
  //Some code in here may cause an exception.
}

What happens when method "B" causes an Exception? Does the program crash? Should "B" declare "throws Exception" in the method declaration?

2
  • 4
    Have you tried it? It may take just 2 minutes to test it and know the results. Commented Jul 12, 2011 at 5:18
  • As @Harry mentioned try it first.. it will give you more understanding rather when reading the answers.. after that if you are not clear then post a question.. Commented Jul 12, 2011 at 5:21

3 Answers 3

3

If method B is throwing some checked exception then it should declare throws exception statement.

Sign up to request clarification or add additional context in comments.

Comments

1

It all boils down to Checked Exception vs. Unchecked Exception.

Unchecked Exceptions are subclasses from RuntimeException. They can be thrown without the need to be declared in the method signature. If they are not caught they are thrown further up the stack. So if B throws an unchecked Exeption A will throw it up, too. The compiler won't check whether Unchecked Exceptions are handled, you'll see that only at runtime, hence the name RuntimeException.

Checked Exceptions need to be declared in the signature and must be handled or the method signature of the calling method must state that the Exception is thrown. Otherwise the compiler will complain and you wont' be able to compile the program. So if B throws a CheckedException like a FileNotFoundException you have to declare it in B's signature. Since A does not catch it it get's thrown further. Declaring A to throw Exception does work in that case, but it's bad practice.

Comments

0

If Exception occurs it will be catched by the most nearest catch block. If the catch is not present in the current function it will bubble up until it finds any relevant catch block.

If you declare explicitly that the function might throw an error and caller must take care of that situation then we declare throws with the function signature for typed exception.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.