Exception Handling
JavaScript includes a try ... catch ... finally
exception handling statement to handle run-time errors.
The try ... catch ... finally
statement catches exceptions resulting from an error or a throw statement. Its syntax is as follows:
Initially, the statements within the try block execute. If an exception is thrown, the script's control flow immediately transfers to the statements in the catch block, with the exception available as the error argument. Otherwise the catch block is skipped. The Catch block can throw(errorValue)
if it does not want to handle a specific error.
In any case the statements in the finally block are always executed. This can be used to free resources, although memory is automatically garbage collected.
Either the catch
or the finally
clause may be omitted. The catch argument is required.
The Mozilla implementation allows for multiple catch statements, as an extension to the ECMAScript standard. They follow a syntax similar to that used in Java:
try { statement; } catch (e if e == "InvalidNameException") { statement; } catch (e if e == "InvalidIdException") { statement; } catch (e if e == "InvalidEmailException") { statement; } catch (e) { statement; }In a browser, the onerror
event is more commonly used to trap exceptions.
Read more about this topic: Java Script Syntax
Famous quotes containing the words exception and/or handling:
“For a parent, its hard to recognize the significance of your work when youre immersed in the mundane details. Few of us, as we run the bath water or spread the peanut butter on the bread, proclaim proudly, Im making my contribution to the future of the planet. But with the exception of global hunger, few jobs in the world of paychecks and promotions compare in significance to the job of parent.”
—Joyce Maynard (20th century)
“Many more children observe attitudes, values and ways different from or in conflict with those of their families, social networks, and institutions. Yet todays young people are no more mature or capable of handling the increased conflicting and often stimulating information they receive than were young people of the past, who received the information and had more adult control of and advice about the information they did receive.”
—James P. Comer (20th century)