1

Can we use try and catch block in constructor or can we throw an exception from constructor or throws exception on constructor in java Is this is a good practice to have try and catch block, throw and throws into constructor in java or a bad practice? Please guide me through, awaits reply and thank you in advance.

Akshay
  • 91
  • 1
  • 9

2 Answers2

2

There's nothing wrong with throwing an exception in a constructor just as there's nothing wrong with throwing an exception anywhere else.You should handle only those exceptions that you can recover from just as you would do in any other part of your code. In some cases e.g initializing a JSONObject you may have to catch or throw an exception. Just make sure that this exceptions are properly handled

Nyakiba
  • 862
  • 8
  • 18
1

It's not a good practice. but you have a statement which is fire the Exception than you can throws Exception consider following example.

public class Test {
static int no;
Test() throws Exception {
    no=Integer.parseInt("5"); 
}
public static void main(String[] args) {
    try{new Test();}catch(NumberFormatException error){
        no=0; }
    System.out.println(no);

}
}
dhaval joshi
  • 490
  • 1
  • 3
  • 15