Suppose there is a class with a constructor with parameters, inside which a check for correctness of the arguments is provided. And here is the question: how to handle the error that occurred in the constructor? I first of all thought to generate exceptions and take the class object declaration into the try block, but immediately faced the problem that the object is being created, exceptions are caught, but the object outside the try block is not visible. Then how to handle errors in the constructor correctly?
|
2 answers
If the arguments are incorrect, then the class object cannot be created and you just need to throw exception through throw . This exception should be handled by code that initiated an attempt to create an object with erroneous arguments.
In another case, in this situation, it would be possible to create an object with default arguments that are clearly correct. But this will only veil the problem of erroneous arguments, which is not very good.
- those. just generate an exception, but do not try to intercept it? - WenSiL
- @WenSiL if the problem can be solved in place (right in the constructor), then no exceptions are needed at all. An exception allows you to transfer error handling to the level where it is clear what to do with this error. - 伪位蔚蠂慰位蠀蟿
- I understand you, thank you. - WenSiL
|
The general approach is to declare a variable before the try block, try to initialize it inside the block and use it after.
- those. It turns out that a constructor with parameters does not make much sense to create? Will it be easier and more correct to write a method that will perform exactly the same functions? - WenSiL
|