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:
“It has no share in the leadership of thought: it does not even reflect its current. It does not create beauty: it apes fashion. It does not produce personal skill: our actors and actresses, with the exception of a few persons with natural gifts and graces, mostly miscultivated or half-cultivated, are simply the middle-class section of the residuum.”
—George Bernard Shaw (18561950)
“For a novel addressed by a man to men and women of full age; which attempts to deal unaffectedly with the fret and fever, derision and disaster, that may press in the wake of the strongest passion known to humanity; to tell, without a mincing of words, of a deadly war waged between flesh and spirit; and to point the tragedy of unfulfilled aims, I am not aware that there is anything in the handling to which exception can be taken.”
—Thomas Hardy (18401928)