In Java, how to remove catch try block inside constructor for input / output code

In Java How can I write I / O code that should be in a try catch block inside a constructor without try-catch in a costructor? As with a method, we can throw an exception to the calling method by writing throws in the defination method, and we can remove the try-catch. how can we remove try-catch in the constructor for input / output code. This is the question the interviewer asked me. I said that this cannot be done, and I really have no idea. Guys, what do you think. Please suggest

+3
source share
3 answers

Use this:

public class Foo
{
   public Foo() throws IOException
   {
       doSomeIO();
   }
}
+8

The same thing can be done with methods. Just declerare cast expression.

, .:)

+2

throws , .

+1

All Articles