JavaScript Tutorial/Development/assert
Assert method
<source lang="javascript">
<html> <head> <title>Debug Example</title> <script type="text/javascript">
function assert(bCondition, sErrorMessage) { if (!bCondition) { alert(sErrorMessage); throw new Error(sErrorMessage); } }
function aFunction(i) { assert(false, "1==2"); } aFunction(1);
</script> </head> <body>
This page uses assertions to throw a custom JavaScript error.
</body> </html></source>
Catch exception throwed from assert function
<source lang="javascript">
<html>
<head> <title>Try Catch Example</title> <script type="text/javascript"> function assert(bCondition, sErrorMessage) { if (!bCondition) { throw new Error(sErrorMessage); } }
try { assert(1 == 2, "Two numbers are required."); } catch (oException) { alert(oException.message); //outputs "Two numbers are required." } </script> </head> <body> </body>
</html></source>