2

I would like to know what happens in java if a method call signature has a exception but there is no try catch block in the method what happens when a exception happens at runtime.

public void someMethod (Collection<file> files) throws Exception
for(File f : files) {    
    process(f);
} 
1
  • it gets thrown on up the call stack. By definition. Commented Aug 20, 2011 at 5:52

4 Answers 4

3

A method's throwing an exception is a separate concept from having code in a method that catches an exception:

Exceptions thrown inside a try/catch are eligible to be caught by catch blocks on that construct.

When a method declares it throws one or more exceptions, then that type of exception may be thrown out of that method to be caught by another. Note that unchecked exceptions don't need to be declared. They just go their merry way without letting anyone know what's up.

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

Comments

2

There are two thing in java exception handling mechanism

  1. Exception Throwing
  2. Exception handling (with a catch() block).

In this case your someMethod()throws an exception. If any method use this method then it has to catch and handle the exception. If the calling method of someMethod() does not handle the exception then any one method in the method call hierarchy must catch() and handle the exception.

Comments

1

Then the exception thrown will be propagated to the method caller and the method caller have to deal with it (either catch it or declare itself that it will throw exception).

Comments

1

an exception is just another type of return for a function. if you don't catch it in this function, it will be passed to the next. and if that function cant catch it, then that function will also pass the exception to the function which called it and the chain goes on until you finally reach a catch block for it where it is handled or the jvm prints its stack trace through system.out.

Hope this helps!

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.