File tree 1 file changed +24
-1
lines changed
1 file changed +24
-1
lines changed Original file line number Diff line number Diff line change @@ -16,4 +16,27 @@ setTimeout(function () {
16
16
} catch {
17
17
console . log ( "error is caught here!" ) ;
18
18
}
19
- } , 1000 ) ;
19
+ } , 1000 ) ;
20
+
21
+ //If an exception happens in “scheduled” code, like in setTimeout, then try...catch won’t catch it
22
+ try {
23
+ setTimeout ( function ( ) {
24
+ noSuchVariable ; // script will die here
25
+ } , 1000 ) ;
26
+ } catch ( err ) {
27
+ console . log ( "won't work" ) ; //that’s because the function itself is executed later, when the engine has already left the try...catch construct.
28
+ }
29
+
30
+ //To catch an exception inside a scheduled function, try...catch must be inside that function:
31
+
32
+ setTimeout ( function ( ) {
33
+ try {
34
+ noSuchVariable ; // try...catch handles the error!
35
+ } catch {
36
+ console . log ( "error is caught here!" ) ;
37
+ }
38
+ } , 1000 ) ;
39
+
40
+
41
+ //Error Object
42
+ //When an error occurs, JavaScript generates an object containing the details about it. The object is then passed as an argument to catch
You can’t perform that action at this time.
0 commit comments