JavaScript personal learning notes Summary - error handling

Posted by lookielookies on Tue, 08 Mar 2022 13:32:42 +0100



contentwebsite
JavaScript personal learning notes Summary - quick starthttps://blog.csdn.net/weixin_50594210/article/details/115112096?spm=1001.2014.3001.5501
JavaScript personal learning notes Summary - functionhttps://blog.csdn.net/weixin_50594210/article/details/115113081?spm=1001.2014.3001.5501
JavaScript personal learning notes Summary - standard objecthttps://blog.csdn.net/weixin_50594210/article/details/115112683?spm=1001.2014.3001.5502
JavaScript personal learning notes Summary - object oriented programminghttps://blog.csdn.net/weixin_50594210/article/details/115113024?spm=1001.2014.3001.5502
JavaScript personal learning notes Summary - browserhttps://blog.csdn.net/weixin_50594210/article/details/115113131
JavaScript personal learning notes Summary - jQueryhttps://blog.csdn.net/weixin_50594210/article/details/115113299
JavaScript personal learning notes Summary - error handlinghttps://blog.csdn.net/weixin_50594210/article/details/115113442
Updating ingUpdating ing

error handling

  when executing JavaScript code, errors will occur in some cases.

   there are two kinds of errors. One is that the logic of the program is wrong, resulting in abnormal code execution. For example:

var s = null;
var len = s.length; // TypeError: null variable has no length attribute

For this error, fix the program.

   one is that during execution, the program may encounter unpredictable abnormal conditions and report errors, such as network connection interruption, reading nonexistent files, lack of operation authority, etc.

For this error, we need to deal with it and may need to give feedback to users.

  error handling is a problem that must be considered in program design. For C, a language close to the bottom of the system, the error is returned through the error code:

int fd = open("/path/to/file", O_RDONLY);
if (fd == -1) {
    printf("Error when open file!");
} else {
    // TODO
}

  to return an error through an error code, you need to agree on what is the correct return value and what is the wrong return value. The above open() function convention returns - 1, indicating an error.

  obviously, this kind of error code is very inconvenient when writing programs.

  therefore, high-level languages usually provide more abstract error handling logic try... catch... finally, and JavaScript is no exception.

Analyze the execution process using try... catch... finally.

<script>
		var r1, r2, s = null;
	try {
    	r1 = s.length; // An error should occur here
    	r2 = 100; // The statement will not be executed
	} catch (e) {
    	console.log('Error:' + e);
	} finally {
    	console.log('finally');
	}
	console.log('r1 = ' + r1); // r1 should be undefined
	console.log('r2 = ' + r2); // r2 should be undefined
</script>

   contemporary code block is tried {...} When wrapping, it means that errors may occur during the execution of this part of the code. Once an error occurs, it will not continue to execute the subsequent code, but skip to the catch block. catch (e) { ... } The code of the package is the error handling code, and the variable E represents the captured error. Finally, with or without errors, finally will be executed.

Therefore, when an error occurs, the execution process is like this:

  1. try {...} Code of;
  2. When an error statement is executed, the subsequent statements will no longer continue to execute, but instead execute catch (e) {...} code;
  3. finally execute {...} code.

When no error occurs, the execution process is like this:

  1. try {...} Code of;
  2. Because there is no error, catch (e) {...} The code will not be executed;
  3. finally execute {...} code.

  finally, please note that catch and finally do not have to appear at all. In other words, the try statement has three forms:

Complete try... catch... finally:

try {
    ...
} catch (e) {
    ...
} finally {
    ...
}

Only try... catch, not finally:

try {
    ...
} catch (e) {
    ...
}

Only try... finally, no catch:

try {
    ...
} finally {
    ...
}
  • Error type

   JavaScript has a standard Error object to represent errors, as well as Error objects such as TypeError and ReferenceError derived from Error. When dealing with errors, we can access the Error object through the variable e captured by catch(e):

<script>
	try {
    	...
	} catch (e) {
    	if (e instanceof TypeError) {
        	alert('Type error!');
    	} else if (e instanceof Error) {
        	alert(e.message);
    	} else {
        	alert('Error: ' + e);
    	}
	}
</script>

   using the variable e is a idiom and can also be named after other variables, such as catch(ex).

  • Throw error

   the program can also actively throw an error and let the execution process jump directly to the catch block. Throw an error using the throw statement.

  in fact, JavaScript allows you to throw arbitrary objects, including numbers and strings. However, it is better to throw an Error object.

Finally, when catching errors with catch, we must write error handling statements:

<script>
	var n = 0, s;
	try {
    	n = s.length;
	} catch (e) {
    	console.log(e);
	}
	console.log(n);
</script>

Don't do nothing even if you just print out the error:

<script>
	var n = 0, s;
	try {
    	n = s.length;
	} catch (e) {
	}
	console.log(n);
</script>

   because catch finds an error but does not execute anything, you don't know whether there is an error in the process of program execution.

   when handling errors, please do not use alert() to display errors to users simply and rudely. The code in the tutorial uses alert () for demonstration purposes.

1. Error propagation

  if the code has an error and is not captured by try... catch, where will the program execution flow jump?

<script>
	function getLength(s) {
    	return s.length;
	}

	function printLength() {
    	console.log(getLength('abc')); // 3
    	console.log(getLength(null)); // Error!
	}

	printLength();
</script>

   if an error occurs inside a function and it is not captured, the error will be thrown to the outer layer to call the function. If the outer function is not captured, the error will be thrown upward along the function call chain until it is captured by the JavaScript engine and the code terminates execution.

   therefore, we don't need to catch errors in each function, but we just need to catch them uniformly in the right place and catch them all in one net:

<script>
	function main(s) {
    	console.log('BEGIN main()');
    	try {
        	foo(s);
    	} catch (e) {
        	console.log('Error:' + e);
    	}
    	console.log('END main()');
	}

	function foo(s) {
	    console.log('BEGIN foo()');
	    bar(s);
    	console.log('END foo()');
	}

	function bar(s) {
    	console.log('BEGIN bar()');
    	console.log('length = ' + s.length);
    	console.log('END bar()');
	}

	main(null);
</script>

   when bar() function passes in null parameter, the code will report an error, and the error will be thrown up to the caller foo() function. Foo() function has no try Catch statement, so the error continues to be thrown up to the caller's main() function. The main() function has try Catch statement, so the error is finally handled in the main () function.

2. Asynchronous error handling

   when writing JavaScript code, always keep in mind that the JavaScript engine is an event driven execution engine. The code is always executed in a single thread, and the execution of callback function will not be executed until the next qualified event occurs.

For example, the setTimeout() function can pass in a callback function and execute after a specified number of milliseconds:

<script>
	function printTime() {
    	console.log('It is time!');
	}

	setTimeout(printTime, 1000);
	console.log('done');
</script>

The above code will print done first and It is time! After 1 second!.

   if an error occurs inside the printTime() function, our attempt to wrap setTimeout() with try is invalid:

<script>
		function printTime() {
    	throw new Error();
	}

	try {
    	setTimeout(printTime, 1000);
    	console.log('done');
	} catch (e) {
    	console.log('error');
	}

</script>

   the reason is that when calling the setTimeout() function, the printTime function passed in is not executed immediately! Next, the JavaScript engine will continue to execute console log('done'); Statement, and no error occurs at this time. The error does not occur until one second later when the printTime function is executed, but at this time, the outer code cannot catch the error except inside the printTime function.

   therefore, when asynchronous code is involved, it cannot be captured at the time of call, because the callback function is not executed at the time of capture.

   similarly, when we process an event, the error of the event handler cannot be captured at the code binding the event.

For example, for the following forms:

<form>
    <input id="x"> + <input id="y">
    <button id="calc" type="button">calculation</button>
</form>

Bind click event to button:

<script>
	var $btn = $('#calc');

	// Unbind events:
	$btn.off('click');



	try {
    	$btn.click(function () {
        	var
            	x = parseFloat($('#x').val()),
            	y = parseFloat($('#y').val()),
            	r;
        	if (isNaN(x) || isNaN(y)) {
            	throw new Error('Incorrect input');
        	}
        	r = x + y;
        	alert('Calculation results:' + r);
    	});
	} catch (e) {
    	alert('Wrong input!');
	}
</script>



Note: part of the summary comes from the official website of Liao Xuefeng!

Topics: Java Javascript Front-end Back-end