- Home /
How to yiled a try/catch block?
Hi
I have a WWWhelper class to get resources. In case of fails, we usually set a try/catch for it so it can notice user try again later.
IEnumerator TryGet(){
try{
//some codes here may throw exception
yield return StartCoroutine(WWWHelper.Get());
}
catch{
Debug.log("Oops");
}
}
Unfortunately, the Editor said
Cannot yield a value in the body of a try block with a catch clause
So how can I make it ? Thank you
I think the problem seems to be that when you 'yield' the Coroutine can't really get in contact back with the try{}catch{} block, as it has been 'sent' to another execution space in the game code that is not longer reachable by try/catch.
So I guess the answer to your problem will be to implement a local try{}catch{} on the inside of the WWWHelper.Get() method? So then you just launch the Coroutine knowing that it will inform itself if something went wrong on it's inside codes?
@CodeAssembler Yes that's work. But it looks better if decouple our code, say, make WWWHelper to handle all WWW requests and scripts focus on calls and feed back. In other word, we may unable to expect what's going to feed back for each call(such as network fail, target ain't exists etc.), although catched exception inside of WWWHelper.
Hence I'm wondering is there any way to let game knows that WWWHelper.Get fails(like throw it as usual) so we can handle exceptions manually.
Oh, get it.
@CodeAssembler please post your comment as answer so it can be marked and vote up :]
I converted @CodeAssembler's comment to an answer :)
Answer by CodeAssembler · Aug 12, 2013 at 06:04 AM
I think you should check this link, I feel it explains best what I'm trying to tell you : http://answers.unity3d.com/questions/24640/how-do-i-return-a-value-from-a-coroutine.html
Answer by Ted-Bigham · May 20, 2015 at 11:55 PM
A pretty clean way to manage try/catch with WWW is to have the helper coroutine exit normally regardless of result. Then have a getter for the response value, which throws an exception if there was an error.
IEnumerator TryGet()
{
WWWHelper helper = new WWWHelper();
yield return StartCoroutine(helper.Get());
try{
//some codes here may throw exception
helper.GetValue();
}
catch{
Debug.log("Oops");
}
}