Flash / Flex / ActionScript/Statement/finally

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

Control-Flow Changes in try/catch/finally

   <source lang="java">

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.");
   }
 }

}

       </source>
   
  


The finally Block

   <source lang="java">

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) {
       }
   }
 }

}

       </source>
   
  


The finally block can be useful for cleaning up. You can use try and finally together:

   <source lang="java">

/* 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.

}

  • /
       </source>
   
  


Throws an exception in a finally block.

   <source lang="java">

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);
       }
     }
   }
 }

}

       </source>
   
  


Using return in finally

   <source lang="java">

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

}

       </source>