Ошибка action script

ActionScript is a scripting language primarily used for creating interactive and animated content in Adobe Flash and Adobe Animate. While working with ActionScript, encountering errors is not uncommon. These errors can disrupt the functionality of your code and prevent your Flash or Animate project from running smoothly. In this article, we will explore the common causes of ActionScript errors, various types of errors, troubleshooting techniques, best practices for prevention, error handling strategies, debugging tools, and provide examples to help you effectively deal with ActionScript errors.

Understanding ActionScript

Before diving into the intricacies of ActionScript errors, it’s essential to have a basic understanding of ActionScript itself. ActionScript is an object-oriented scripting language, based on ECMAScript, which is the standardized scripting language also used by JavaScript. It enables developers to create interactive animations, games, and other multimedia applications.

Want to fix more errors? Read our article on error: roomba error 43

Common Causes of ActionScript Errors

ActionScript errors can stem from various sources. Understanding the common causes can help you identify and rectify errors more effectively. Some of the typical causes include:

1. Syntax Errors

Syntax errors occur when the code violates the rules and structure of the ActionScript language. These errors often result from missing semicolons, parentheses, or improper variable assignments.

2. Runtime Errors

Runtime errors occur when an error is detected during the execution of the ActionScript code. These errors can include issues such as null object references, division by zero, or accessing undefined variables.

3. Logic Errors

Logic errors occur when the code does not produce the expected outcome. These errors can be tricky to identify as they do not cause the code to crash but rather lead to incorrect or undesired results.

4. Compatibility Issues

Compatibility issues arise when the ActionScript code is not compatible with the Flash Player or Animate version you are using. This can result in errors due to deprecated or unsupported features.

Want to fix more errors? Read our article on error: whirlpool stove error codes

Types of ActionScript Errors

ActionScript errors can be categorized into different types based on their nature and impact. Understanding these error types can assist in troubleshooting and resolving issues efficiently. Here are some common types of ActionScript errors:

1. Syntax Errors

Syntax errors occur when the code violates the syntax rules of ActionScript. These errors are usually caught during the compilation phase and prevent the code from executing.

2. Runtime Errors

Runtime errors occur during the execution of the code and can cause unexpected crashes or issues. These errors often occur due to logical mistakes, incorrect variable usage, or improper handling of exceptions.

3. Null Reference Errors

Null reference errors occur when an object reference is null or undefined, and you attempt to access its properties or methods. These errors can be particularly challenging to debug as they often occur at runtime.

4. Type Errors

Type errors occur when there is a mismatch between the expected data type and the actual data type used in the code. These errors can arise when assigning incompatible values to variables or passing incorrect arguments to functions.

How to Troubleshoot ActionScript Errors

Troubleshooting ActionScript errors requires a systematic approach to identify the root cause and resolve the issues effectively. Here are some steps you can follow:

1. Review Error Messages and Stack Traces

When encountering an ActionScript error, carefully read the error message and examine the stack trace.

Error messages often provide valuable information about the specific issue and the line of code where the error occurred.

2. Check for Syntax Errors

Start by checking for any syntax errors in your code. Carefully review the code and ensure all semicolons, parentheses, and braces are properly placed. Additionally, verify that variable names and function calls are spelled correctly.

3. Debugging Techniques

Use debugging techniques to identify and isolate the cause of the error. This can involve inserting trace statements or breakpoints in your code to track the flow and values of variables during execution.

4. Comment Out Code Sections

If you suspect a particular section of your code is causing the error, temporarily comment out that section and check if the error persists. This can help narrow down the problematic code.

5. Test in Different Environments

Test your ActionScript code in different environments and versions of Flash Player or Animate. Compatibility issues can sometimes be resolved by switching to a different version or using feature detection techniques.

Best Practices to Prevent ActionScript Errors

Preventing ActionScript errors is always better than dealing with them after they occur. By following best practices, you can minimize the chances of encountering errors in your ActionScript code. Consider the following guidelines:

1. Consistent Code Formatting

Maintain consistent code formatting throughout your project. Indentation, naming conventions, and commenting practices can significantly enhance code readability and reduce errors.

2. Use Strong Typing

Utilize strong typing whenever possible to enforce data type integrity. Declare variables with specific data types and utilize the type-checking capabilities of ActionScript to catch errors during compilation.

3. Test Your Code

Thoroughly test your ActionScript code at regular intervals. Implement unit tests and perform integration testing to ensure the desired functionality and identify potential issues before they manifest.

4. Follow Modular Programming Principles

Break your code into modular components, promoting reusability and easier maintenance. By isolating functionalities into separate modules or classes, you can minimize the impact of errors and improve code organization.

5. Stay Updated

Stay informed about the latest updates, changes, and best practices in ActionScript development. Keeping up with the community and official resources can help you stay ahead of potential errors caused by deprecated features or outdated techniques.

ActionScript Error Handling

Effective error handling is crucial for robust ActionScript applications. By implementing proper error handling techniques, you can gracefully handle errors and provide meaningful feedback to users. Consider the following approaches:

1. Try-Catch Statements

Enclose potentially error-prone sections of code within try-catch blocks. This allows you to catch and handle exceptions gracefully, preventing your application from crashing.

2. Error Logging

Implement error logging mechanisms to track and record errors that occur during runtime. This can help you identify recurring issues and provide insights for future improvements.

3. User-Friendly Error Messages

Display user-friendly error messages to guide users when errors occur. Avoid exposing technical details that may confuse or overwhelm non-technical users.

Tools for Debugging ActionScript Errors

To streamline the debugging process, several tools are available that can assist you in identifying and resolving ActionScript errors. Here are some popular debugging tools:

1. Adobe Scout

Adobe Scout is a powerful profiling and optimization tool for ActionScript projects. It provides detailed insights into memory usage, performance bottlenecks, and code execution flow.

2. Flash Builder

Flash Builder is an integrated development environment (IDE) by Adobe specifically designed for ActionScript and Flex development. It offers debugging features such as breakpoints, variable inspection, and step-by-step code execution.

3. Monster Debugger

Monster Debugger is an open-source debugging tool for ActionScript and Adobe AIR projects. It allows

you to inspect variables, trace execution flow, and monitor network activity during runtime.

ActionScript Error Examples

To better understand ActionScript errors, let’s explore a few examples:

1. Syntax Error Example:

var message:String = "Hello, world!"
trace(message)

In this example, the missing semicolon at the end of the first line would result in a syntax error.

2. Runtime Error Example:

var x:int = 10;
var y:int = 0;
var result:Number = x / y;

In this case, the division by zero would cause a runtime error, as dividing by zero is mathematically undefined.

Conclusion

ActionScript errors are an inherent part of the development process when working with Flash and Animate projects. By understanding the common causes, types of errors, and implementing effective troubleshooting techniques, you can minimize the impact of these errors on your projects. Following best practices, implementing proper error handling, and utilizing debugging tools will enhance the stability and reliability of your ActionScript applications.

FAQs

Q1. How can I prevent syntax errors in ActionScript?
To prevent syntax errors, ensure that you follow the correct syntax rules of ActionScript, including using semicolons, parentheses, and braces appropriately. Regularly reviewing and testing your code can help catch syntax errors early.

Q2. What are some common runtime errors in ActionScript?
Common runtime errors in ActionScript include null object reference errors, type errors, and division by zero errors. These errors typically occur during the execution of the code.

Q3. Can I debug ActionScript code in Adobe Animate?
Yes, Adobe Animate provides debugging capabilities for ActionScript. You can set breakpoints, inspect variables, and step through the code to identify and resolve errors.

Q4. Are there any specific tools for debugging ActionScript errors?
Yes, there are several tools available for debugging ActionScript errors, including Adobe Scout, Flash Builder, and Monster Debugger. These tools provide features such as profiling, variable inspection, and execution flow analysis.

Q5. How important is error handling in ActionScript development?
Error handling is essential in ActionScript development as it allows you to gracefully handle errors and provide a better user experience. Proper error handling can prevent application crashes and provide meaningful feedback to users.

An ActionScript error has occurred – words that can grind productivity to a halt, but what if we told you it doesn’t have to be so? Inside the world of Flash Player, complications are common, but so are solutions, particularly the unconventional ones we’ve curated for you.An Actionscript Error Has Occurred

Prepare for an enlightening journey that uncovers methods slightly off the beaten path to get you back on track swiftly and efficiently. Dive in with us as we decode and demystify these perplexing errors and inject momentum into your workday.

Contents

  • Why an Actionscript Error Has Occurred? Several Common Culprits
    • – Faulty Code Syntax or Script
    • – Using an Outdated Flash Version
    • – Security Restrictions and Mishandled External Resources
  • How to Fix an Actionscript Error Has Occurred? Conventional Fixes
    • – Proofread Your Code Snippet
    • – Upgrading to the Latest Version
    • – Proper Handling of External Resources
  • Conclusion

Why an Actionscript Error Has Occurred? Several Common Culprits

ActionScript errors often occur due to various factors: faulty code syntax, outdated Flash Player versions, security restrictions, or poorly handled external resources. Identifying and rectifying these common culprits can help resolve such issues, ensuring a smoother workflow.

It’s a question that we often grapple with in our digital endeavors. Although the debugging approaches are straightforward and only take a minute, learning about the meaning is beneficial and prevents other complications.

Hence, to decode this mystery, let’s investigate a few scenarios where these errors are common culprits. You have likely experienced some obstacles in your programming journey.

Let’s start with incorrect code syntax – the equivalent of misplaced punctuation in a sentence. When scripting, any minor mistake can wreak havoc on the entire program. A missing semicolon, an extra bracket, or even a misnamed variable can easily trigger an ActionScript error. It’s like leaving a shoe in the middle of a racetrack, and it won’t take long before someone stumbles.

Next, think about your Flash Player. It’s like your vehicle: if you don’t update and maintain it regularly, it’ll start giving you trouble. If you’re using an outdated version of Flash Player, it might not support newer ActionScript features, leading to errors. It’s similar to trying to read a brand-new book in an ancient language – you’re bound to hit a snag.Reasons of Actionscript Error Has Occurred

Lastly, we can’t overlook the role of security restrictions and mishandled external resources. Imagine hosting a party (your website) and hiring a DJ (an external resource). If your party venue (the security protocols) doesn’t allow the DJ’s equipment inside, you have a problem. Similarly, an error will occur if Flash Player’s security restrictions prevent ActionScript from accessing an external resource.

These scenarios only represent the tip of the iceberg, but they’re a good place to start understanding why ActionScript errors can occur. Remember, a good troubleshooter always knows where to look first.

– Faulty Code Syntax or Script

Oh, the power of a misplaced semicolon! A minor mishap like an unclosed bracket, a mistyped keyword, or an incorrect function can create errors when coding in ActionScript.

For instance, consider the following:

“`

var x:int;

x = “Hello, World!”;

“`

In this snippet, an integer type variable is incorrectly assigned a string value, which would certainly lead to a syntax error.

Remember, coding is like preparing a gourmet meal. Just as a chef needs to follow the recipe correctly, paying attention to the sequence, quantity, and method, programmers must also respect syntax rules to avoid unpalatable outcomes.

– Using an Outdated Flash Version

Imagine trying to run the latest games on an old computer. Sounds problematic. That’s precisely the situation when using an outdated Flash Player version. This older version may not support newer ActionScript features, causing a conflict.Using Outdated Flash Version

Here’s an example:

“`

Trace (Vector. <int> ([1, 2, 3, 4, 5]));

“`

This code uses the Vector object introduced in ActionScript 3.0. But if you’re using a Flash Player version prior to 10, it’ll stumble on this feature.

To ensure compatibility, it’s crucial to stay updated with Flash Player versions, much like keeping your vehicle tuned for optimum performance.

– Security Restrictions and Mishandled External Resources

Think of your website as a gated community. The guards at the gate (security restrictions) ensure that only authorized people (resources) can enter. But suppose an unrecognized guest (an external resource) tries to come in. In that case, it will be denied entry, leading to a security error.

For instance, trying to load an external image into your Flash movie might lead to a security error if not properly handled:

“`

var url: String = “http://externalwebsite.com/image.jpg”;

var urlReq:URLRequest = new URLRequest (url);

var loader: Loader = new Loader();

loader.load (urlReq);

“`

If the external website doesn’t permit access, this code will run into security restrictions.

Understanding security protocols and resource handling can prevent many headaches, ensuring your digital home remains safe and operational.

How to Fix an Actionscript Error Has Occurred? Conventional Fixes

To fix an ActionScript error, conventional approaches involve checking and rectifying code syntax, ensuring Flash Player is up-to-date, and correctly managing security restrictions and external resources. These systematic steps usually eliminate most errors, promoting a seamless coding experience, especially with complex projects.

When an ActionScript error pops up on your screen, it’s natural to feel a tad overwhelmed. But fret not, as we dive into a few conventional fixes that could turn your coding journey around.How to Fix an Actionscript Error Has Occurred

Firstly, remember the power of proofreading. It’s simple but surprisingly effective. Much like how you’d review an essential email before hitting send, taking a second look at your code can reveal syntax issues triggering errors.

This could be an unclosed bracket, a mistyped variable, or a missing semicolon. It’s the little things that often cause the most significant trouble.

Next, think about your Flash Player version. If you’re still using an old version, it’s like attempting to run a marathon in a pair of worn-out shoes. It’s just not going to end well. But on the other hand, upgrading to the latest version can often resolve many errors and compatibility issues. Plus, you enjoy all the newer features and tools – a win-win.

Lastly, let’s talk about handling external resources and security restrictions. It’s like playing with a jigsaw puzzle where every piece needs to fit perfectly. Any misstep could trigger an error. Ensuring proper handling of external resources and complying with Flash Player’s security guidelines can prevent these errors.

Anyway, the key to resolving ActionScript errors often lies in the basics. Keeping your code neat, your Flash Player updated, and your security checks in place are all part of maintaining a smooth and hassle-free coding journey.

– Proofread Your Code Snippet

Like an author proofreads a novel before publication, a programmer should review their code snippet before execution. Still, this practice often reveals minor mistakes that can create significant errors.

For instance, consider the following faulty code:

“`

var x: int;

x = “Hello, World!”;

“`

This code would indicate an error because the integer variable ‘x’ is assigned a string value. The fix is simple. All you must do is provide an integer value:

“`

var x: int;

x = 10;

“`

By proofreading your code, you can catch and correct such errors, ensuring your ActionScript runs smoothly. It’s much like meticulously checking the ingredients of your favorite recipe to ensure the dish turns out perfect.

– Upgrading to the Latest Version

Operating on an outdated Flash Player version is like navigating a city with an old map. You’re bound to hit some roadblocks. Ensuring your Flash Player is up-to-date can prevent many compatibility issues.

Let’s say you’re running the following code:

“`

Trace (Vector. <int> ([1, 2, 3, 4, 5]));

“`

This won’t work on Flash Player versions before 10, which do not support the Vector object. Upgrading your Flash Player ensures compatibility with the latest features, smoothing your coding journey.

– Proper Handling of External Resources

When working with external resources, the process should be as well-orchestrated as a ballet. Any misstep can lead to an error.Handling of External Resources

Consider this code:

“`

var url: String = “http://externalwebsite.com/image.jpg”;

var urlReq: URLRequest = new URLRequest(url);

var loader: Loader = new Loader();

loader.load (urlReq);

“`

If the external website prevents Flash Player from accessing the image, this code will trigger a security error. The fix? Ensuring your website has the correct cross-domain policy in place. Doing so allows your Flash application to interact seamlessly with external resources, and, much like a well-practiced dance, all the pieces fall perfectly into place.

Conclusion

So, we’ve embarked on an enlightening journey, haven’t we? From understanding the common culprits behind ActionScript errors to diving deep into conventional fixes, we’ve unraveled the knots of this perplexing issue, as recapped in the following bullet list:

  • ActionScript errors often occur due to various factors: faulty code syntax, outdated Flash versions, security restrictions, or poorly handled external resources.
  • Older Flash versions may not support newer ActionScript features, causing a conflict.
  • The critical role of managing security restrictions and external resources.
  • The value of proofreading code snippets to identify and correct mistakes.
  • Conventional approaches to fix an ActionScript error involve checking and rectifying code syntax, ensuring Flash is up-to-date, and correctly managing security restrictions.

With these insights in your toolkit, you’re now equipped to handle any ActionScript error that comes your way. Remember, each mistake is an opportunity to learn, grow, and become a better programmer, so let’s continue to learn, adapt, and excel in our coding journey.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

На этом уроке ActionScript мы рассмотрим один вопрос:

  1. Тестирование на ошибки ActionScript

Для того чтобы протестировать код на ошибки ActionScript Вы должны просмотреть Ваш flash-фильм при помощи Flash Player’a. Вы можете сделать это в любой момент, следуя той инструкции, которая описана ниже.

Если Вы опытный flash-дизайнер, то Вы, наверняка, уже знакомы с возможностью быстрого просмотра ролика, нажав клавиши Ctrl + Enter. Ваш flash-фильм будет запущен непосредственно во Flash CS5, т.е. в интегрированной среде разработки (IDE).

Если Ваш ActionScript-код содержит ошибки, то на панели компайлера (compiler) появится сообщение об ошибке ActionScript, в котором Вы увидите номер строки в коде где произошла ошибка и её краткое описание. Чтобы устранить ошибку Actionscript Вы должны:

  • закрыть Flash Player
  • исправить ошибку
  • вновь протестировать Ваш flash-ролик

В случае множественных ошибок во время тестирования, Вы должны устранять их последовательно, тестируя каждый раз после исправления очередной ошибки Actionscript, т.к. одна ошибка в коде может вызвать несколько сообщений. Если Ваш ActionScript-код содержит функцию trace, то вывод результата ее работы будет отображаться в Output panel (панель вывода). О функции trace мы поговорим подробнее в соответствующем уроке «Проверка переменных».

При добавлении ActionScript-кода в Ваш проект Вы очень часто будете пользоваться панелью Actions. Вы можете тестировать Ваш flash-фильм в любое время, даже тогда когда панель Actions открыта. Вы даже сможете тестировать его не сохраняя на жестком диске компьютера.

Тестирование на ошибки Actionscript

В главном меню программы Flash CS5 щелкните на пункте меню Control (Контроль), затем Test Movie (тестировать фильм) и Test (тестировать)

Тестирование на ошибки ActionScript

Также Вы можете использовать сочетание клавиш Ctrl + Enter.

Flash Player откроется и начнется воспроизведение Вашего flash-фильма.

Flash Player

После усвоения материала этого урока мы можем непосредственно перейти к таким темам как объединение (конкатенация) строк, создание массива ActionScript и добавление и удаление элементов в массив.

I need some help solving some compile errors.

I was following a tutorial (at http://www.youtube.com/watch?v=E8oM808ETWs) and typed down all of the code displayed in the video. When I tried to publish, I was presented two compile errors:

Scene=Scene 1, layer=action, frame=1, Line 16 ‘{‘ expected
Scene=Scene 1, layer=action, frame=1, Line 33 Syntax error.

Here is the code that I have

import flash.external.ExternalInterface
import gfx.motion.Tween
_global.gfxExtentions = true;

var angle:Number;

function init()
{
    _root.Health._yrotation = 30;
    _root.Ammo._yrotation = 30;
    angle = 0;
}

init();

_root.onEnterFrame = function();
{
    angle +=0.1;
    var sined:Number = Math.sin(angle) + 2;
    sined /=2;

    _root.Health.Title._z = -200 * sined;
    _root.Health.Bar._z = -500 * sined;
    _root.Health.Value._z = -200 * sined;
    _root.Health.Background._z = 200 * sined;

    _root.Ammo.Title._z = -200 * sined;
    _root.Ammo.Bar._z = -500 * sined;
    _root.Ammo.Value._z = -200 * sined;
    _root.Ammo.Background._z = 200 * sined;

    _root.Weapon._z = -200 * sined;
}

Jason Sturges's user avatar

asked Jun 24, 2012 at 15:01

jSoftApps's user avatar

_root.onEnterFrame = function(); // <-- lose this semi-colon
{

answered Jun 24, 2012 at 15:06

D. A. Terre's user avatar

D. A. TerreD. A. Terre

6,1021 gold badge18 silver badges18 bronze badges

2

Scene=Scene 1, layer=Layer 1, frame=1, Line 3 ‘)’ expected

attachMovie(‘basket’,’basket’, 2, {_x: Stage.width-50, _y: Math.random()*(Stage.height:-150) +50});

answered Oct 9, 2016 at 12:52

unknown's user avatar

1

Try..catch..finally statement in Actionscript 3 September 22, 2010

Posted by Tournas Dimitrios in Actionscript.

trackback

In Actionscript , errors can be generated both by the Flash runtime (Built-in errors) and by the program that is executing (custom-errors) . In a program , we can respond to , or handle , any error via the try/catch/finally statement. ActionScript 3 is much less forgiven in letting you get away with mistakes or code conflicts. Whereas ActionScript 1 and 2 may silently fail or ignore many errors, ActionScript 3 will be sure to let you know something went wrong. Errors belong to the following categories :

  • Synchronous Errors
  • Asynchronous Errors

Synchronous Errors :

Normal errors in code which occur as a code block is being executed are synchronous errors. When the Flash player encounters one of these errors in code, an error, or exception, is thrown. At that point the Flash player will suspend all code in the current block and prevent it from continuing unless the exception is taken care of or caught. To catch exceptions in ActionScript, you use a try..catch..finally statement.

The try..catch..finally statement lets you try a block of code possible of throwing an error and react accordingly if an error occurs. It consists of 2 or more blocks of code: an initial try block, consisting of the code that could throw an error, 1 or more catch blocks that catch errors of different types and run if that type of error is thrown, and an optional finally block which is run after the try and any catches whether or not an error occurs. Its format is as follows:

try {
// potential error causing code
} catch (error:Error) {
// error of type Error occurred
// additional catch blocks may follow
} finally {
// optional to follow try and catch blocks
}

f an exception is thrown within a try block, Flash will look through each catch block until a matching error type is found. When a match is found, that code is run followed by the finally block if it exists. Any additional code following a try..catch..finally statement will be executed as normal even if an error occurs because it was caught by the try..catch..finally statement.

Throw custom errors :

Errors are not thrown exclusively by Flash. You also have the ability to throw errors in your own code if you so desire. To throw errors you would use the throw statement. The throw statement throws any value that precedes it (namely an Error object). When thrown, the error will act just like any error and would require a try..catch..finally block to be correctly caught.

// Throwing your own errors in ActionScript
throw new Error(”Error message”);
//A more practical example 
function divideIt(first:Number, second:Number) :Number {
	
	if(second === 0) {
		throw new Error("You cannot divide by 0.");
	} else {
		return first / second;
	}
	
}

try {
	trace(divideIt(20, 10));
	trace(divideIt(20, 0));
}
catch (e:Error) {
	trace(e);
}

Throwing your own errors can be a helpful debugging tool, especially as you work with more complicated applications.

Asynchronous Errors :

Errors can also occur during asynchronous actions, such as loading external content, and take the form of events. These errors cannot be caught with try..catch..finally statements. Instead you have to create event handlers to handle and “catch” the error events. If you do not have an event listener assigned to an error event and that error occurs, the Flash player will inform you of the unhandled error event.

// creating listeners for error events handles
// asynchronous errors
target.addEventListener(ErrorEvent.TYPE, handler);
function handler(event:ErrorEvent):void {
// handle error
}

Creating Asynchronous Errors :

If you want to invoke your own asynchronous errors, all you need to do is dispatch an event using dispatchEvent that is of the type ErrorEvent. When an unhandled ErrorEvent reaches the Flash player when authoring in Flash, the output window will display the error.

// target object is an event dispatcher
// that needs to dispatch an error event
target.dispatchEvent(new ErrorEvent(”type”));

Release and Debug Players

The release of the Flash player is available in two versions, the release and debug. The release player is the standard, public player. This player is what you will have installed for your browser(s) when you download and install Flash player from adobe.com.

The debug player is an alternate player with additional debug information and capabilities embedded within it. This makes the player a little heftier in file size (which is why its not preferred for distribution) but also provides popup dialogs for uncaught exceptions and unhandled asynchronous errors – something the public would rather not see when your Flash movie or application runs into a snag. For developers, however, this player provides useful information when testing your movies.

You can find installers for both the release and debug players in the Players folder within your Flash CS3 (or older) install directory.

One thing to keep in mind is that just because the release player doesn’t visually show an error when an exception is thrown, it doesn’t mean that error line is simply ignored like with previous versions of ActionScript. The code block where that error occurred will be exited and the remaining script ignored.
Example: Loading external text with error handling

To load text content from an external source into the Flash player, you would use the URLLoader class. An instance of URLLoader will load a text file into its data property to be read as a string. Because the process of locating, downloading, and reading an external file into the Flash player takes time, events are used to indicate when the content has been loaded and is available. Not only that, events are used to indicate loading progress and also any errors that occur.

The URLLoader class uses the load method to start the loading process which is also capable of throwing exceptions of many different error types. When using the URLLoader class to load external content, its always best to listen for all asynchronous errors as well as call the load method within a try..catch..finally statement.

// load textfile.txt text into loader instance
var request:URLRequest = new URLRequest(”textfile.txt”);
var loader:URLLoader = new URLLoader();

// listen for complete event (and others if desired)
loader.addEventListener(Event.COMPLETE, loadComplete);
// listen for error events
loader.addEventListener(IOErrorEvent.IO_ERROR, loadIOError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loadSecurityError);

// complete event handler
function loadComplete(event:Event):void {
trace(loader.data); // textfile.txt contents
}
// handler for IO error
function loadIOError(event:IOErrorEvent):void {
trace(”IOError: “+event);
}
// handler for security error
function loadSecurityError(event:SecurityErrorEvent):void {
trace(”SecurityError: “+event);
}

// try the load operation and
// catch any thrown exceptions
try {
loader.load(request);
}catch (error:ArgumentError){
trace(”ArgumentError: “+error);
}catch (error:MemoryError){
trace(”MemoryError: “+error);
}catch (error:SecurityError){
trace(”SecurityError: “+error);
}catch (error:TypeError){
trace(”TypeError: “+error);
}catch (error:Error){
trace(”Unknown Error: “+error);
}

In the above example, each error event has its own listener tracing the error if an error occurs during loading. Additionally, each type of error thrown by the load operation is being checked within respective catch blocks. An ending catch with the type Error is used in case there was an error thrown not within the other catches. Then that final block would catch the error no matter what it was. And really, you could just have one catch of the type Error to handle all error events. Similarly one event handler could be used for all error events. In doing this you can still catch and handle all errors but it would involve less code.

// load textfile.txt text into loader instance
var request:URLRequest = new URLRequest(”textfile.txt”);
var loader:URLLoader = new URLLoader();

// listen for complete event (and others if desired)
loader.addEventListener(Event.COMPLETE, loadComplete);
// listen for error events using one handler
loader.addEventListener(IOErrorEvent.IO_ERROR, loadError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loadError);

// complete event handler
function loadComplete(event:Event):void {
trace(loader.data); // textfile.txt contents
}
// handler for errors
function loadError(event:ErrorEvent):void {
trace(”Error: “+event);
}

// try the load operation and
// catch any thrown exceptions
try {
loader.load(request);
}catch (error:Error){
trace(”Error: “+error);
}

Here, all errors are still accounted for but less code is involved.

Note that the event parameter of the loadError method is typed as ErrorEvent. Just like all errors thrown by Flash are also of the type Error as well as their own type (their classes extend the Error class), the event errors are also of the type ErrorEvent. By typing the event parameter as ErrorEvent, you can be sure that whatever type of error occurs, it will correctly match with the type of event used in the event handler.

Понравилась статья? Поделить с друзьями:
  • Ошибка abs ford transit
  • Ошибка action not supported
  • Ошибка a830 bmw e60
  • Ошибка abs ford kuga
  • Ошибка act 39 при активации eset