
Hello everyone. I hope you are doing well.
I am Julian Toppo and today we will learn more about error handling and it’s implementation. We will also learn how we handled empty input values in the previous video.
Error handling is like having a plan or dealing with mistakes when they happen.
Let me share a story about a to-do app I created.
I was excited that my friends would use it,
but soon, they started facing problems.
The app crashed when users submitted tasks with empty fields or special characters.
This was because my code didn’t handle errors properly.
Luckily, I learned my lesson about the importance of error handling.
Let’s try to understand error handling
by taking an example of an airport security check.
Airport security is strict.
They have clear rules on what you can bring.
For example, you can only carry 100 ml of liquid.
You can’t bring flammable items like lighters.
Sharp objects like knives are also not allowed.
These are the basics, but rules can vary a bit .
-Why do you think there’s so much strictness?
Let a person with a gun sneaks into the airport.
This is dangerous for everyone. It could disrupt airport operations.
To prevent this, we check for weapons during security.
This way, we stop problems before they start.
So Being proactive helps keep everyone safe.
Similarly in coding:
Errors can crash your app or cause incorrect results.
Instead of waiting for a crash, we handle errors ahead of time.
(New Additions after this)
Implementation Example:
Let’s go back to the example of a form
When we are writing code to read the name and age value in the form
errors can come anywhere.
In this code, the error could occur if there’s a misspelled word or
if we are trying to access something that is not present.
Let’s say (referring to the code) we are trying to access the name using the event. target,
But wait we have misspelled the word name and we are using “.value” for it.
This will result in standard predefined errors like Type errors .
This will cause our application to work incorrectly.
Take a look:
Wouldn’t it be better if we could handle the code,
without disrupting the flow of our application.
For implementing this we enclose the code which will result in possible errors inside the try block.
This will ensure that any potential error inside the block is handled.
Will show the code implementation of error occuring using.
Catch:
Now that error is occurring. Who will handle it?
The error occurring in the try block is caught by the catch block.
Let’s have a look:
It processes the error, typically by logging an error message or performing other error recovery actions.
This helps us in handling errors more efficiently without crashing the whole application or displaying incorrect results in our case no results.
Will show the code implementation of error handling using code.
Throw:
In addition to handling standard errors such as Type Errors, Reference Errors, and Syntax Errors,
we can also raise custom errors based on specific conditions in our code.
Extra custom errors help us specify problems easily,
which makes fixing them simpler.
They also give clearer messages to developers and users, making the app work better.
For example, if we need to check that the name and age fields aren’t empty,
we can create a custom error.
If either field is empty, it will show a message like,
Value of age or name cannot be empty.”
This message is one we’ve created to improve the app and is
not just a standard JavaScript error.
Let’s take a look at how we can implement this.
If we go by the traditional format of checking whether the element is empty or not.
- Form Inputs: You manually check if inputs like name and age are valid, not empty, and correctly formatted.
Each condition has its own error handling. - DOM Elements: You also check if elements accessed with getElementById exist, handling errors separately if they’re missing.
Will show the code implementation of error handling using code.
One of the biggest disadvantage of doing this :
- Repetitive Code: Each if statement has its own error-handling logic.
- Manual Control: You need to manage the flow and error handling manually for each condition
So if you want to raise an error when some values are empty,
you can use throw new Error(“Your custom message here”).
This lets you show a clear message about what went wrong,
making it easier to fix the problem.
Let’s take a look:
A try block helps make error handling easier by
putting all the checks for line of code in one place.
This way, you don’t need to write multiple if statements for different errors.
Centralized Management:
If something goes wrong inside the try block,
then an error will be triggered
which will be caught in the catch block.
Instead of handling each error separately,
the catch block provides a single place to manage
all errors.
For example
The errors are thrown while accessing name and age
can be accessed in the catch block.
We can use this error to notify the user about
the error or use it for creating error reports.
It deals with the error, without stopping the entire application.
Let’s take a look at the code:
Will show the code implementation of error handling using throw.
Advantages:
- Cleaner Code: Keeps error handling in one place, reducing repetitive code.
- Automatic Flow Control: The catch block handles errors thrown in the try block automatically.
- Easier Management: Manages all errors in one spot, making the code easier to maintain.
Using a try block makes error handling more efficient and organized.
Finally:
Now we want to keep track of how many times the form is submitted.
Also need to show a list of all the information submitted through the form.
We can do this using a special section of the code called finally
This is update the submission count and list of entries
, even if there are mistakes during submission.
Let’s understand how It Works:
- The user fills out the form with a name and age and clicks the “Submit” button.
- The code checks if the name and age are valid.
- If everything is correct, the entry is added to the list of entries and counts are updated for successful submissions.
- If there are any issues (like missing name or invalid age), the error is caught and the counts for failed submissions are updated.
- The finally block runs no matter if the try block had an error or not.
- It updates the total form submissions.
Will show the code:
Let’s say we have initialized a variable called totalSubmission =0 and it get’s incremented with every submission.
finally {
// Always update counters and list
totalSubmissions++;
document.getElementById(‘totalCount’).textContent = totalSubmissions;
// Update the list of all entries
updateEntriesList();
}
Let’s take a look.
This setup keeps everything organized and count the form submission whether submissions are successful or not.
Summary:
Handling errors is like having a backup plan.
Try and catch help you fix problems without stopping your app,
and finally makes sure everything is cleaned up.
This way, your app stays smooth and reliable.
Thanks for being here today, and keep coding!
Enroll in Sharpener NOW !
At Sharpener Tech, we don’t just teach, we transform careers! Our Pay After Placement model ensures ZERO financial risk you pay only when you land a high-paying job. With industry-driven Full Stack Development training, hands-on projects, and expert mentorship, we guarantee your success in the tech world. Don’t just dream BUILD your future with Sharpener Tech! Apply now and start your journey!