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?
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.