Flash / Flex / ActionScript/Statement/finally — различия между версиями

Материал из Web эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 08:14, 26 мая 2010

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.
    }
  }
}