try { //statements that may cause an error } catch (err) { //err holds info about the error //statements that handle an error, if one happens throw err //if you decide to error after all } finally { //optional //statements that happen error or not }
There are 3 types of errors:
#1 is corrected by the programmer learning and fixing the code. #2 can be fixed by adding more code to better check the data, but it starts to get annoying... #3 can't be fixed... except by a try-catch block. And, they really manes dealing with bad data easy. Just don't deal with it, and reject anything that causes a crash.
The catch block can example the error object and take action based on the type of the error. e.g.
try { something(); } catch (e) { if (e instanceof RangeError) { // statements to handle this very common expected error console.log("out of range"+e) throw "value out of range" } else { throw e; // re-throw the error unchanged } }
The error object also has two attributes: .name which is the general class of error, and .message which is a short error message.
Error classes include:
The throw keyword accepts any expression, or can be used with new to make a new error object of any error class or a generic error. E.g.
throw "bogus" //directly using a string or other value throw my_error_messages(32) //function can return a value for the error throw new Error("bogus") //generic error with message throw new TypeError("value must be a widget") //error of type TypeError
See also:
file: /Techref/language/JAVA/SCRIPT/try-catch-finally.htm, 2KB, , updated: 2020/3/1 23:27, local time: 2024/8/14 19:26,
18.188.150.210:LOG IN
|
©2024 These pages are served without commercial sponsorship. (No popup ads, etc...).Bandwidth abuse increases hosting cost forcing sponsorship or shutdown. This server aggressively defends against automated copying for any reason including offline viewing, duplication, etc... Please respect this requirement and DO NOT RIP THIS SITE. Questions? <A HREF="http://piclist.com/techref/language/JAVA/SCRIPT/try-catch-finally.htm"> JavaScript Try Catch Finally</A> |
Did you find what you needed? |
![]() o List host: MIT, Site host massmind.org, Top posters @none found - Page Editors: James Newton, David Cary, and YOU! * Roman Black of Black Robotics donates from sales of Linistep stepper controller kits. * Ashley Roll of Digital Nemesis donates from sales of RCL-1 RS232 to TTL converters. * Monthly Subscribers: Gregg Rew. on-going support is MOST appreciated! * Contributors: Richard Seriani, Sr. |
Welcome to piclist.com! |
.