try, catch, finally, throw - error handling in JavaScript
Skills:
Algorithm Basics70%
Key Takeaways
Explains error handling in JavaScript using try, catch, finally, and throw
Full Transcript
Errors can be coding errors made by the programmer, errors due to wrong input, or other unforeseeable things. I will be discussing how to handle errors in JavaScript. Error handling is used most when working with data from other sources or user input, since those can be unreliable. It is common to see error handling associated with Ajax calls and asynchronous code. Error handling uses the keywords try, catch, finally, and throw. The try statement lets you test a block of code for errors. The catch statement lets you handle the error. The throw statement lets you create custom errors. And the finally statement lets you execute code after try and catch, regardless of the result. So, let's see some code. Okay, here's the first part. We're going to try some code to see if there's going to be any error, and then we're going to console.log start of try runs, and then this part right here is the error, because there is nothing in the program called unicycle. And then it's going to try to run some more code here. And then it's going to catch the error. And then we're going to have the finally statement. I'm going to run this, and then we'll talk about what's in the logs here. So, start of try runs, that's right here. And then it reached the error. So, since the error was reached here, it never goes to this next statement. Once the error is reached, it goes straight to the catch statement right down here. It says, "Error has occurred. Reference error, unicycle is not defined at pen.js 14 3." So, it we pass in an error object to the catch statement, and then I'm I'm to console.log error has occurred, and then we console.log error.stack. Now, .stack is is when it's going to show this part right here. We can also do it without the .stack where we just log the error. And if I run that, you're going to see this part. And this is what's going to be used usually. Not all browsers can handle the the .stack. So, when the error occurs, JavaScript generates an object containing the details about it. So, so that's what the error object is. And it's going to have two main properties, name and message. So, the name is the reference error right here, and then the message is unicycle is not defined. And then I also already showed you about getting the the call stack. Then it's going to go down to the finally statement, whether or not an error happens, we're going to always run the code in the finally statement. This is always run. And then at the end, you can see the execution continues. So, that's just after the the try catch statement is over, it continues. Now, for the try catch to work, the code must be runnable. In other words, it should be valid JavaScript. It won't work if the syntax is wrong. Like if I have a an opening brace here, and then I don't have the ending brace, and then if I if I try to run that, well, that's not going to work. This is called a parse time error. Well, try catch only handles run time errors. So, the code has to be able to run. So, I'm just going to delete that here, and then run that, and then we can actually see it run this time. There are many built-in errors that already exist, but you can also create your own custom errors with the throw statement. I'm going to talk about throw errors in the context of a more realistic use case for try catch statements. Okay, let's say you're going to get data from a server. Often from a server you're going to get JSON data, sometimes through an Ajax call, but we're just going to to like we got this data from a server and then we're going to try this. Let user equal JSON.parse. So, we're going to parse the data that we got from the server. And then, if there is no user.name, we're going to throw a new syntax error, incomplete data, no name. So, let's say we're expecting the data from the server to have a name, but this doesn't have a name. So, we're going to throw a new syntax error and put incomplete data, no name. Now, you can actually throw a number or a string or or a boolean. But, also you can create a new error, like a new syntax error or a new error, and you can pass in the message. So, syntax error is going to be the name of the error, and then this is going to be the message of the error. So, if I run that, you'll see what I mean. So, you can see down here we're going to console.log JSON error, and then we're just going to log the message, e.message. So, the message is incomplete data, no name. The name of the error will be syntax error. So, if we log the e.name down here, I run that, you'll see JSON error, syntax error. Or, we can just log the entire thing and just do e, and it's going to say JSON error, syntax error, incomplete data, no name. So, it got the JSON error, then it says the syntax error, that's the name of the error right here, and then it's going to have the message incomplete data, no name. So, in this code, if there was a name, it would console.log the name, but there's not a name. As soon as it throws this error here, it's going to go to the catch statement, and that's when it logs the error statement right here. So, that's the basics of error handling in JavaScript. Check the description for a link to more information, and also to the code used. Thanks for watching. My name is Beau Carnes. Don't forget to subscribe, and remember, use your code for good.
Original Description
Error handling in JavaScript uses the keywords: try, catch, finally, and throw.
💻 Code: https://codepen.io/beaucarnes/pen/rwBmWE?editors=0012
🔗 https://javascript.info/try-catch
🐦 Beau Carnes on Twitter: https://twitter.com/carnesbeau
⭐JavaScript Tutorials Playlists⭐
▶JavaScript Basics: https://www.youtube.com/playlist?list=PLWKjhJtqVAbk2qRZtWSzCIN38JC_NdhW5
▶Data Structures and Algorithms: https://www.youtube.com/playlist?list=PLWKjhJtqVAbkso-IbgiiP48n-O-JQA9PJ
▶Design Patterns: https://www.youtube.com/playlist?list=PLWKjhJtqVAbnZtkAI3BqcYxKnfWn_C704
▶ES6: https://www.youtube.com/playlist?list=PLWKjhJtqVAbljtmmeS0c-CEl2LdE-eR_F
▶Clean Code: https://www.youtube.com/playlist?list=PLWKjhJtqVAbkK24EaPurzMq0-kw5U9pJh
-
Learn to code for free and get a developer job: https://www.freecodecamp.com
Read hundreds of articles on technology: https://medium.freecodecamp.com
And subscribe for new programming videos every day: https://youtube.com/subscription_center?add_user=freecodecamp
❤️ Support for this channel comes from our friends at Scrimba – the coding platform that's reinvented interactive learning: https://scrimba.com/freecodecamp
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from freeCodeCamp.org · freeCodeCamp.org · 14 of 60
1
2
3
4
5
6
7
8
9
10
11
12
13
▶
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
React: Production Server Setup Part 2 - Live Coding with Jesse
freeCodeCamp.org
cookies vs localStorage vs sessionStorage - Beau teaches JavaScript
freeCodeCamp.org
Browser history tutorial - Beau teaches JavaScript
freeCodeCamp.org
Graph Data Structure Intro (inc. adjacency list, adjacency matrix, incidence matrix)
freeCodeCamp.org
React: Parameterized Routing with Next.js - Live Coding with Jesse
freeCodeCamp.org
React: Dealing with jQuery Issues - Live Coding with Jesse
freeCodeCamp.org
setInterval and setTimeout: timing events - Beau teaches JavaScript
freeCodeCamp.org
Browser and Device Testing - Live Coding with Jesse
freeCodeCamp.org
Last Minute Updates - Live Coding with Jesse
freeCodeCamp.org
Post Launch Updates - Live Coding with Jesse
freeCodeCamp.org
React: Setting Up Google Analytics - Live Coding with Jesse
freeCodeCamp.org
React: Masonry Layout - Live Coding with Jesse
freeCodeCamp.org
Load Balancing Digital Ocean Droplets - Live Coding with Jesse
freeCodeCamp.org
try, catch, finally, throw - error handling in JavaScript
freeCodeCamp.org
Load Balancing: SSL Passthrough Setup - Live Coding with Jesse
freeCodeCamp.org
Graphs: breadth-first search - Beau teaches JavaScript
freeCodeCamp.org
React: Masonry Layout Part 2 - Live Coding with Jesse
freeCodeCamp.org
React: WordPress API Live Search - Live Coding with Jesse
freeCodeCamp.org
Creating WordPress Custom Post Types - Live Coding With Jesse
freeCodeCamp.org
Dates - Beau teaches JavaScript
freeCodeCamp.org
Miscellaneous Front End Updates - Live Coding with Jesse
freeCodeCamp.org
Merging a Pull Request from GitHub - Live Coding with Jesse
freeCodeCamp.org
React + Prettier + Standard JS - Live Coding with Jesse
freeCodeCamp.org
React: Sortable Responsive Table - Live Coding with Jesse
freeCodeCamp.org
Geolocation Sorting by Distance - Live Coding with Jesse
freeCodeCamp.org
Tradeoff Matrix - Agile Software Development
freeCodeCamp.org
The Definition of Ready - Agile Software Development
freeCodeCamp.org
Getting first React job without experience - Ask Preethi
freeCodeCamp.org
React: Google Analytics Click Tracking - Live Coding with Jesse
freeCodeCamp.org
Submitting a PR to an Open Source Project - Live Coding with Jesse
freeCodeCamp.org
Should I go back to school to get CS degree? - Ask Preethi
freeCodeCamp.org
Hero Section CSS Changes - Live Coding with Jesse
freeCodeCamp.org
Working Agreement - Agile Software Development
freeCodeCamp.org
A day at Pennybox with Co-Founder Reji Eapen
freeCodeCamp.org
React: Sorting and Filtering Data - Live Coding with Jesse
freeCodeCamp.org
React: Sorting and Filtering Data Part 2 - Live Coding with Jesse
freeCodeCamp.org
React: Building a New UI - Live Coding with Jesse
freeCodeCamp.org
Definition of Done - Agile Software Development
freeCodeCamp.org
Getting started with jQuery (tutorial) - Beau teaches JavaScript
freeCodeCamp.org
Making a React Blog with WordPress Content - Live Coding with Jesse
freeCodeCamp.org
React, NextJS, CSS - Live Coding with Jesse
freeCodeCamp.org
jQuery events - Beau teaches JavaScript
freeCodeCamp.org
React/NextJS Routing and WordPress API Custom Types - Live Coding with Jesse
freeCodeCamp.org
React: Working with API Data - Live Coding with Jesse
freeCodeCamp.org
React: Refactoring Components - Live Streaming with Jesse
freeCodeCamp.org
jQuery effects - Beau teaches JavaScript
freeCodeCamp.org
More React Refactoring - Live Coding with Jesse
freeCodeCamp.org
animate in jQuery - Beau teaches JavaScript
freeCodeCamp.org
"Finishing" My React Site - Live Coding with Jesse
freeCodeCamp.org
Starting a New React Project (P2D1) - Live Coding with Jesse
freeCodeCamp.org
React Project 2 Day 2: Learning Material UI - Live Coding with Jesse
freeCodeCamp.org
The Agile Manifesto - Agile Software Development
freeCodeCamp.org
jQuery: get and set with http, text, val, and attr - Beau teaches JavaScript
freeCodeCamp.org
React Project 2 Day 3 - Live Coding with Jesse
freeCodeCamp.org
The INVEST approach to product backlog items
freeCodeCamp.org
React Project 2 Day 4 - Live Coding with Jesse
freeCodeCamp.org
Chickens and Pigs - Agile Software Development
freeCodeCamp.org
React Project 2 Day 5 - Live Coding with Jesse
freeCodeCamp.org
jQuery: add and remove DOM elements - Beau teaches JavaScript
freeCodeCamp.org
React Project 2 Day 6 - Live Coding with Jesse
freeCodeCamp.org
More on: Algorithm Basics
View skill →
🎓
Tutor Explanation
DeepCamp AI