Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Finally code
Message
Information générale
Forum:
ASP.NET
Catégorie:
Autre
Titre:
Divers
Thread ID:
00970841
Message ID:
00971024
Vues:
21
Don't know what the problem is but here's how it should be:
private void Test()
{
	IPEndPoint ipEP;
	Socket udpSocket;
	try
	{
		// some code
		ipEP = new IPEndPoint(paraIPAddress, iPort);
		udpSocket = new Socket(ipEP.Address.AddressFamily,SocketType.Dgram,ProtocolType.Udp);
		// some more code
	}
	catch(Exception ex)
	{
		//Do something if exception is thrown
	}
	finally
	{
		//I need some code here to test if the socket is created/initialized
		if (udpSocket !=null)
			udpSocket.Close();
	}

}
>Del and Stephane,
>Correct for a trivial example like an int I can just initialize it, but my original problem is for a Socket
>
>Socket udpSocket = new Socket(ipEP.Address.AddressFamily,	SocketType.Dgram,	ProtocolType.Udp)
>
>and if I initialize the Socket before the try block I am SOL if the initilazation of the Socket throws an error.
>
>I hope this makes sense.
>
>Einar
>
>>I've run into the same thing with if/else constructs. Initializing the variable with a value seems to resolve it;
>>
>>int myInt = 0;
>>
>>>I tried what you sugested, but I got a compile error that stated that myObject had not been initialized I found that very odd because that is what I want to check for in the finally block.
>>>
>>>Here is a little console app I wrote to ilustrate:
>>>
>>>int myInt;
>>>try
>>>{
>>>	myInt = 1;
>>>}
>>>finally
>>>{
>>>	if (myInt != 1)
>>>	{
>>>		myInt = -4;
>>>	}
>>>}
>>>Console.WriteLine(myInt.ToString());
>>>
>>>
>>>This gives me the following error:
>>>use of unassigned local variable myInt
>>>in line 10 (if (myInt != 1))
>>>
>>>Any clue?
>>>
>>>Einar
>>>
>>>
>>>
>>>>2. You get an exception because your variable is out of scoop in the finally block. Declare if before the try:
>>>>
>>>>
>>>>Object myObject;
>>>>try
>>>>{
>>>>     myObject = new SomeThing();
>>>>...
>>>>}
>>>>finally
>>>>{
>>>>    if (myObject !=null)
>>>>    {...}
>>>>}
>>>>
>>>>
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform