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.
Asked
Active
Viewed 2,827 times
1
-
1Bad practice, but it's not black-or-white. – Marko Topolnik Oct 13 '16 at 08:48
2 Answers
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
-
2`catch Exception(..)` is a sure way to fail the next code review, even if this just a quick and dirty example one should use the proper `NumberFormatException`, IMHO. – Gyro Gearless Oct 13 '16 at 09:08
-