September 18, 2002 - Catching, Manipulating, and Throwing Exceptions
September 18, 2002 Catching, Manipulating, and Throwing Exceptions Tips: September 2002
Yehuda Shiran, Ph.D.
|
null
parameter with two nested try...catch
blocks. The function TryCatchDemo()
throws string exceptions from one block to the other. One exception is thrown from the inner try
block to the inner catch
block. Another exception is thrown from the inner catch
block to the outer catch
block. We call the function TryCatchDemo()
twice: once with a null argument, and once with an array:
print(TryCatchDemo(null)+ "\n");
print(TryCatchDemo(new Array(5)));
The following Command Prompt window shows the listing of the function TryCatchDemo()
and the two calls shown above. The window also shows how to compile the code (throw2.js
), and the response of the function to these two calls. When we pass a null
value, the response is "x equals null and handled in inner catch block"
. When we pass a real array, the response is "x does not equal null, error handled in outer catch block"
. Notice that each final exception string is built by the exception handling block that catches the exception and throws it farther to the outer block. If x
is null, the inner try
block throws "x equals null"
. The inner catch
block catches this exception and, just before returning, adds a few words to the exception string (" and handled in inner catch block"
). If x
is not null
, the inner try
block throws "x does not equal null"
. The inner catch
block catches this exception and throws it up again. The outer catch
block catches this exception and, just before returning, adds a few words to the exception string (" , error handled in outer catch block"
). Here is the Command Prompt window:To learn more about exception handling, go to Column 118, JScript .NET, Part XII: Exception Handling.