Java Reference
In-Depth Information
Next comes the catch statement. The code included exception in parentheses right after the catch
statement. This exception is simply a variable name. It will store an object, of type Error, containing
information about any exception thrown during code execution inside the try code block. We'll call this
object the exception object . Although the word exception is used here, you can use any valid variable
name. For example, catch(exceptionObject) would be fi ne and certainly more descriptive.
The exception object contains several properties that provide information about the exception that
occurred. The bad news is the exception object in IE differs somewhat from the exception object in
other browsers (and even Firefox, Opera, Safari, and Chrome have differing properties from each
other!). The good news is there are similarities, and you don't have to worry about writing cross-
browser code if you're only concerned with the exception's message and the type of exception.
All major browsers support the name and message properties. The name property contains the name
of the error type, and the message property contains the error message the user would normally see.
These properties are part of the ECMAScript 3 standard.
Back to the code at hand, within the curly braces after the catch statement is the code block that will
execute if and only if an exception occurs. In this case, the code within the try code block is fi ne, and
so the alert() method inside the catch block won't execute.
Insert a deliberate error.
try
{
alert('This is code inside the try clause');
ablert ('Exception will be thrown by this code');
}
catch(exception)
{
alert(“The error is “ + exception.message);
}
Resave the document and reload the page in your browser. The fi rst alert() method in the try block
of code executes fi ne and the alert box will be displayed to the user. However, the second ablert()
statement will cause an error and code execution will start at the fi rst statement in the catch block.
If you're using Internet Explorer, the error description displayed will be Object expected. If you're
using another browser, the same error is interpreted differently and reported as ablert is not
defined.
If you change the code again, so that it has a different error, you'll see something important.
try
{
alert('This is code inside the try clause');
alert('This code won't work');
}
catch(exception)
{
alert(“The error is “ + exception.message)
}
Search WWH ::




Custom Search