This can be achieved in Java by throwing an exception from your constructor. Since constructors cannot return a value, this is the only way to perform error handling.
Class MyCLass{ private int x; File file; MyClass() throws MyException{ x = 10; try{ file = new File(“c:\myFile.txt”); } catch(Exception e) { throw new MyException(); } / / } }
When you use this class, insert the code of the constructor in a try-catch block and catch the exception:
try{ MyClass mc = new MyClass(); } catch(MyException e) { System.out.println(“Could not create an object of the classMyClass”); }