Throwing exception during object creation | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
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 Respostas
+ 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