- Home /
Why is my Try and Catch not working?
Hello, I have a very annoying problem. I have my game save all these variables to a certain file path that I believe should work on all computers but, in case it doesn't work I would like my game to notice that it fails to save and show up a GUI box saying my custom fail message to the player. So I tried this:
// Close the file (^ above is where I write the var's into the file)
saveStream.Close();
try
{
throw saveStream.Close ();
}
catch (err)
{
MoveAround.saveFailed = true;
return;
}
// Give confirmation that the file has been saved
print ( "Data Saved at: " + filePath2 + "/" + fileName2 );
MoveAround.saveWork = true;
in the save script's save function, and I get these errors:
'void' is not a valid argument type for throw, only strings and exceptions are allowed.
so um...HOW DO I FIX THIS (I've seen a c# example but not a javascript example of a try+catch)???!!!!! Your help will be greatly appreciated!
Those errors are just incomplete syntax?... fix those and see if you have any actual syntax errors with your code?
I don't know how to...I never did a try catch before...not at all
Answer by Bunny83 · Oct 04, 2011 at 03:44 AM
The keywork throw is used to manually throw an exception. Like the error states: throw must be followed by an instantce of an exception class or a string.
If you just want catch errors that happens during saveStream.Close() just remove the "throw". All eaxceptions that are thrown within a try - catch block are catched by the nearest try-catch-block.
try
{
saveStream.Close ();
}
catch (err)
{
MoveAround.saveFailed = true;
return;
}
Here's a simple example of throw:
try
{
throw "Error, plz abort";
Debug.Log("This will never execute");
}
catch(err)
{
Debug.Log("Exception catched: " + err);
}
ps: the code is not tested and i'm not sure if the syntax is the same in UnityScript
btw: if the saving fails it would most likely fail when you open your stream or when you write to the stream, so you should put that code into the try block and not just the Close()
Agreed. On a related note, what is the type of that err variable? Is that just Exception, that is, the base class?
JavaScript's typing scheme confuses me this way. If that's a FileStream, then the only exception Close can throw is an IOException, and he should be catching that, not the general one. If he decides to add more code to the try-block later, catching the base exception might unintentionally swallow other types of exceptions invisibly, making this harder to debug.