Can someone tell me what difference does it make to create an instance of an object outside / inside the try catch block.
Does it have performance issues?
Thanks
You should place try blocks around any code that you are expecting to throw exceptions...an d that you want to handle.
That's what they are there for.
Like tlhintoq said, if instantiating the object could possibly throw an exception that you want to handle, then place it inside the try block so that you can handle it properly.
If it doesn't throw an exception...the n it's up to you where you instantiate the thing.
If you don't need the object until after attempting to execute code that could potentially throw an exception, then you could instantiate it after that code if you really want to. This could potentially have an effect on performance, but I don't think that you're going to notice the difference.
Another thing to consider is: Is the object supposed to be used out side of the try block? If so, then you have to instantiate it outside of the try block...
This is not a question of "best practice".
This is a question of "how do you need to use the object" and "what is the expected behaviour of the object".
It's not even really a performance question either... if your application requires an object be instantiated, then it requires that the object be instantiated.
Where it's instantiated is up to the design of your application (how you have designed your application to use the object)
I prefer to make my declaration outside the the try/catch block and instanciate (or whatever inside)
For example:
[code=c#]
MyClass obj;
try
{
//stuff to instanciate and work with the object
}
catch(Exception ee)
{
//catch logic
}
[/code]
I prefer to make my declaration outside the the try/catch block and instanciate (or whatever inside)
For example:
[code=c#]
MyClass obj;
try
{
//stuff to instanciate and work with the object
}
catch(Exception ee)
{
//catch logic
}
[/code]
That works but if you need to access the object outside of the TryCatch block then it still has to be instantiated outside of it.
For example:
[code=c#]
MyClass obj;
try
{
//Stuff to try doing
}
catch(Exception ee)
{
//Stuff that fixes the exception
}
//Stuff that uses obj.....which means that obj must exist
//therefore it must be instantiated outside of the try block.
[/code]
That works but if you need to access the object outside of the TryCatch block then it still has to be instantiated outside of it.
Only if it failed.
Otherwise the object is there and you have a reference to it(check for null). The only time I need it is in the catch{} section I like to log an error and need to know details about the object. If its declared only in the try{}, I don't have access to it
Comment