Today I wanted to mess around with error handling in JavaScript, specifically the whole try-catch thing. I’ve seen it in code before, but never really dug into it myself.
Getting Started
First, I created a super simple HTML file. Just the basic structure, nothing fancy. Then, inside a <script> tag, I started typing out the basic structure:
try {
// Code that might cause trouble goes here
} catch (error) {
// What to do if something goes wrong
Looks simple enough, right? The `try` block is where you put the code that you think might cause an error. The `catch` block is what runs if, indeed, something goes wrong.
Making Some Mistakes
So, I needed to make some deliberate errors. I thought, “What’s something that will definitely break?” I decided to try calling a function that doesn’t exist:
try {
thisFunctionDoesNotExist();
} catch (error) {
*("Oops! Something went wrong.");
*(error);
I ran this, and sure enough, the console showed my “Oops!” message, followed by a more detailed error message from JavaScript itself. It said something like “ReferenceError: thisFunctionDoesNotExist is not defined”. Perfect! It’s working as expected.
Getting More Specific
Then I wanted to see if I could catch different types of errors. I remembered reading something about different error types, like `TypeError` and `ReferenceError`. So, I modified my code:
try {
let x = 5;
*(); // Trying to uppercase a number!
} catch (error) {
if (error instanceof TypeError) {
*("That's a type error!");
} else {
*("Some other kind of error:", error);
This time, I’m deliberately trying to use a string method (`toUpperCase()`) on a number. This should cause a `TypeError`. When I ran it, the console correctly showed “That’s a type error!”. So, I can use `instanceof` to figure out what kind of error I’m dealing with.
Adding a `finally`
I also learned about the `finally` block. This is code that runs no matter what, whether there’s an error or not. I added one to my example:
try{
let x = 5;
}catch (error){
if (error instanceof TypeError){
*("That's a type error");
}else{
*("some other kind of error", error)
}finally{
*("this code alaways run");
I did that code and see the console, it correctly showed “this code alaways run”, that’s cool!
Wrapping Up
So, that was my little adventure with try-catch. It’s pretty straightforward, but super useful for making your code more robust. Now, instead of my program just crashing when something goes wrong, I can handle errors gracefully, maybe show a user-friendly message, or try a different approach. It’s all about making things smoother for the user (and for me, the developer!).