Throwing exception during object creation | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Throwing exception during object creation

Say, an object depends on some other object which must not be null and passed via constructor. Is throwing exceptions in a constructor without problems, or would it be ill-advised? 🤔

7th Jan 2022, 10:03 AM
Agnes Ahlberg
Agnes Ahlberg - avatar
3 Answers
+ 1
You may do that only if necessary (ex : the constructor needs a number as param and not an array, so if the param is an array, throw the exception)
7th Jan 2022, 10:07 AM
VCoder
VCoder - avatar
0
Thank you for the response, VCoder ☺ If I understand correctly, then you object generally to throwing exceptions in a constructor 🤔 I was wondering, however, if you could be more specific about your reasoning behind your recommended practice ☺
7th Jan 2022, 1:50 PM
Agnes Ahlberg
Agnes Ahlberg - avatar
0
In truth, you might do this in any method of the object like this function divide(a, b) { if(b == 0) throw "Division by 0 is impossible" // if executed, the program will stop return a / b }
7th Jan 2022, 2:02 PM
VCoder
VCoder - avatar