try, catch, finally, throw - error handling in JavaScript

freeCodeCamp.org · Beginner ·⚡ Algorithms & Data Structures ·9y ago

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 React: Production Server Setup Part 2 - Live Coding with Jesse
React: Production Server Setup Part 2 - Live Coding with Jesse
freeCodeCamp.org
2 cookies vs localStorage vs sessionStorage - Beau teaches JavaScript
cookies vs localStorage vs sessionStorage - Beau teaches JavaScript
freeCodeCamp.org
3 Browser history tutorial - Beau teaches JavaScript
Browser history tutorial - Beau teaches JavaScript
freeCodeCamp.org
4 Graph Data Structure Intro (inc. adjacency list, adjacency matrix, incidence matrix)
Graph Data Structure Intro (inc. adjacency list, adjacency matrix, incidence matrix)
freeCodeCamp.org
5 React: Parameterized Routing with Next.js - Live Coding with Jesse
React: Parameterized Routing with Next.js - Live Coding with Jesse
freeCodeCamp.org
6 React: Dealing with jQuery Issues - Live Coding with Jesse
React: Dealing with jQuery Issues - Live Coding with Jesse
freeCodeCamp.org
7 setInterval and setTimeout: timing events - Beau teaches JavaScript
setInterval and setTimeout: timing events - Beau teaches JavaScript
freeCodeCamp.org
8 Browser and Device Testing - Live Coding with Jesse
Browser and Device Testing - Live Coding with Jesse
freeCodeCamp.org
9 Last Minute Updates - Live Coding with Jesse
Last Minute Updates - Live Coding with Jesse
freeCodeCamp.org
10 Post Launch Updates - Live Coding with Jesse
Post Launch Updates - Live Coding with Jesse
freeCodeCamp.org
11 React: Setting Up Google Analytics - Live Coding with Jesse
React: Setting Up Google Analytics - Live Coding with Jesse
freeCodeCamp.org
12 React: Masonry Layout - Live Coding with Jesse
React: Masonry Layout - Live Coding with Jesse
freeCodeCamp.org
13 Load Balancing Digital Ocean Droplets - Live Coding with Jesse
Load Balancing Digital Ocean Droplets - Live Coding with Jesse
freeCodeCamp.org
try, catch, finally, throw - error handling in JavaScript
try, catch, finally, throw - error handling in JavaScript
freeCodeCamp.org
15 Load Balancing: SSL Passthrough Setup - Live Coding with Jesse
Load Balancing: SSL Passthrough Setup - Live Coding with Jesse
freeCodeCamp.org
16 Graphs: breadth-first search - Beau teaches JavaScript
Graphs: breadth-first search - Beau teaches JavaScript
freeCodeCamp.org
17 React: Masonry Layout Part 2 - Live Coding with Jesse
React: Masonry Layout Part 2 - Live Coding with Jesse
freeCodeCamp.org
18 React: WordPress API Live Search - Live Coding with Jesse
React: WordPress API Live Search - Live Coding with Jesse
freeCodeCamp.org
19 Creating WordPress Custom Post Types - Live Coding With Jesse
Creating WordPress Custom Post Types - Live Coding With Jesse
freeCodeCamp.org
20 Dates - Beau teaches JavaScript
Dates - Beau teaches JavaScript
freeCodeCamp.org
21 Miscellaneous Front End Updates - Live Coding with Jesse
Miscellaneous Front End Updates - Live Coding with Jesse
freeCodeCamp.org
22 Merging a Pull Request from GitHub - Live Coding with Jesse
Merging a Pull Request from GitHub - Live Coding with Jesse
freeCodeCamp.org
23 React + Prettier + Standard JS - Live Coding with Jesse
React + Prettier + Standard JS - Live Coding with Jesse
freeCodeCamp.org
24 React: Sortable Responsive Table - Live Coding with Jesse
React: Sortable Responsive Table - Live Coding with Jesse
freeCodeCamp.org
25 Geolocation Sorting by Distance - Live Coding with Jesse
Geolocation Sorting by Distance - Live Coding with Jesse
freeCodeCamp.org
26 Tradeoff Matrix - Agile Software Development
Tradeoff Matrix - Agile Software Development
freeCodeCamp.org
27 The Definition of Ready - Agile Software Development
The Definition of Ready - Agile Software Development
freeCodeCamp.org
28 Getting first React job without experience - Ask Preethi
Getting first React job without experience - Ask Preethi
freeCodeCamp.org
29 React: Google Analytics Click Tracking - Live Coding with Jesse
React: Google Analytics Click Tracking - Live Coding with Jesse
freeCodeCamp.org
30 Submitting a PR to an Open Source Project - Live Coding with Jesse
Submitting a PR to an Open Source Project - Live Coding with Jesse
freeCodeCamp.org
31 Should I go back to school to get CS degree? - Ask Preethi
Should I go back to school to get CS degree? - Ask Preethi
freeCodeCamp.org
32 Hero Section CSS Changes - Live Coding with Jesse
Hero Section CSS Changes - Live Coding with Jesse
freeCodeCamp.org
33 Working Agreement - Agile Software Development
Working Agreement - Agile Software Development
freeCodeCamp.org
34 A day at Pennybox with Co-Founder Reji Eapen
A day at Pennybox with Co-Founder Reji Eapen
freeCodeCamp.org
35 React: Sorting and Filtering Data - Live Coding with Jesse
React: Sorting and Filtering Data - Live Coding with Jesse
freeCodeCamp.org
36 React: Sorting and Filtering Data Part 2 - Live Coding with Jesse
React: Sorting and Filtering Data Part 2 - Live Coding with Jesse
freeCodeCamp.org
37 React: Building a New UI - Live Coding with Jesse
React: Building a New UI - Live Coding with Jesse
freeCodeCamp.org
38 Definition of Done - Agile Software Development
Definition of Done - Agile Software Development
freeCodeCamp.org
39 Getting started with jQuery (tutorial) - Beau teaches JavaScript
Getting started with jQuery (tutorial) - Beau teaches JavaScript
freeCodeCamp.org
40 Making a React Blog with WordPress Content - Live Coding with Jesse
Making a React Blog with WordPress Content - Live Coding with Jesse
freeCodeCamp.org
41 React, NextJS, CSS - Live Coding with Jesse
React, NextJS, CSS - Live Coding with Jesse
freeCodeCamp.org
42 jQuery events - Beau teaches JavaScript
jQuery events - Beau teaches JavaScript
freeCodeCamp.org
43 React/NextJS Routing and WordPress API Custom Types - Live Coding with Jesse
React/NextJS Routing and WordPress API Custom Types - Live Coding with Jesse
freeCodeCamp.org
44 React: Working with API Data - Live Coding with Jesse
React: Working with API Data - Live Coding with Jesse
freeCodeCamp.org
45 React: Refactoring Components - Live Streaming with Jesse
React: Refactoring Components - Live Streaming with Jesse
freeCodeCamp.org
46 jQuery effects - Beau teaches JavaScript
jQuery effects - Beau teaches JavaScript
freeCodeCamp.org
47 More React Refactoring - Live Coding with Jesse
More React Refactoring - Live Coding with Jesse
freeCodeCamp.org
48 animate in jQuery - Beau teaches JavaScript
animate in jQuery - Beau teaches JavaScript
freeCodeCamp.org
49 "Finishing" My React Site - Live Coding with Jesse
"Finishing" My React Site - Live Coding with Jesse
freeCodeCamp.org
50 Starting a New React Project (P2D1) - Live Coding with Jesse
Starting a New React Project (P2D1) - Live Coding with Jesse
freeCodeCamp.org
51 React Project 2 Day 2: Learning Material UI - Live Coding with Jesse
React Project 2 Day 2: Learning Material UI - Live Coding with Jesse
freeCodeCamp.org
52 The Agile Manifesto - Agile Software Development
The Agile Manifesto - Agile Software Development
freeCodeCamp.org
53 jQuery: get and set with http, text, val, and attr - Beau teaches JavaScript
jQuery: get and set with http, text, val, and attr - Beau teaches JavaScript
freeCodeCamp.org
54 React Project 2 Day 3 - Live Coding with Jesse
React Project 2 Day 3 - Live Coding with Jesse
freeCodeCamp.org
55 The INVEST approach to product backlog items
The INVEST approach to product backlog items
freeCodeCamp.org
56 React Project 2 Day 4 - Live Coding with Jesse
React Project 2 Day 4 - Live Coding with Jesse
freeCodeCamp.org
57 Chickens and Pigs - Agile Software Development
Chickens and Pigs - Agile Software Development
freeCodeCamp.org
58 React Project 2 Day 5 - Live Coding with Jesse
React Project 2 Day 5 - Live Coding with Jesse
freeCodeCamp.org
59 jQuery: add and remove DOM elements - Beau teaches JavaScript
jQuery: add and remove DOM elements - Beau teaches JavaScript
freeCodeCamp.org
60 React Project 2 Day 6 - Live Coding with Jesse
React Project 2 Day 6 - Live Coding with Jesse
freeCodeCamp.org

Related Reads

Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →