Flash / Flex / ActionScript/Statement/finally
Содержание
Control-Flow Changes in try/catch/finally
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
changeFlow ( );
}
public function changeFlow ( ):void {
try {
return;
throw new Error("Test error.");
} catch (e:Error) {
trace("Caught: " + e.message);
} finally {
trace("Finally executed.");
}
trace("Last line of method.");
}
}
}
The finally Block
try {
} catch (e:ErrorType1) {
} catch (e:ErrorTypen) {
} finally {
}
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
try {
try {
throw new Error("Test error");
} catch (e:Error) {
trace(e.message); // Displays: Test error
}
} catch (e:Error) {
}
}
}
}
The finally block can be useful for cleaning up. You can use try and finally together:
/*
try {
// Code to try.
}
finally {
// Code to run regardless.
}
//Or, you can use try, catch, and finally:
try {
// Code to try.
}
catch (erObject:Error) {
// Code to run if the try code throws an error.
}
finally {
// Code to run regardless.
}
*/
Throws an exception in a finally block.
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
try {
throwTwoExceptions( );
} catch (e:Error) {
trace("External catch: " + e.message);
}
try {
throw new Error("Test error 1");
} finally {
try {
throw new Error("Test error 2");
} catch (e:Error) {
trace("internal catch: " + e.message); // Never executes because
// the types don"t match.
}
}
}
public function throwTwoExceptions ( ):void {
try {
throw new Error("Test error 1");
} finally {
try {
throw new Error("Test error 2");
} catch (e:Error) {
trace("Internal catch: " + e.message);
}
}
}
}
}
Using return in finally
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
changeFlow ( );
}
public function changeFlow ( ):void {
try {
throw new Error("Test error.");
} catch (e:Error) {
trace("Caught: " + e.message);
} finally {
trace("Finally executed.");
return;
}
trace("Last line of method."); // Not executed.
}
}
}