3

In Java How can I write I/O code that must be in try catch block inside a Constructor without try-catch in the costructor? Like for a method we can pass the exception to the caller of the method by writing throws in method defination and we can remove try-catch. how we can remove try-catch in a constructor for the I/O code. Thats question asked by a interviewer to me. i said it cant be done and i really dont have an idea. Guys what you think. Please suggest??

3
  • 4
    You do it in the same exact way that you do for a method - by declaring the checked exception in the throws part of the declaration. Commented May 18, 2012 at 10:58
  • Err. create a separate initialize() method and call it on your newly created object? Commented May 18, 2012 at 11:04
  • Oh man, it sounds like you were over thinking the interview question. Commented Jun 8, 2012 at 7:00

3 Answers 3

8

Use this:

public class Foo
{
   public Foo() throws IOException
   {
       doSomeIO();
   }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Same way you do to the methods. Just declerare a throws statement.

Trying this would be easier than typing this long question here though. :)

Comments

1

You can add a throws clause also to a constructor, similarly to any other method.

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.