📌  相关文章
📜  Day 3: Try, Catch, and finally hackerrank 10 天的 javascript 解决方案 - Javascript (1)

📅  最后修改于: 2023-12-03 14:40:38.628000             🧑  作者: Mango

Day 3: Try, Catch, and Finally - HackerRank 10 Days of JavaScript

Introduction

Welcome to Day 3 of HackerRank's 10 Days of JavaScript! Today we will be learning about error handling in JavaScript and how to use the try, catch, and finally statements.

Error Handling

In programming, errors can occur for a wide variety of reasons such as incorrect input, wrong data types, and unexpected behavior in the code. As developers, it is important to properly handle these errors to ensure that our code runs smoothly and doesn't crash.

Try, Catch, and Finally Statements

JavaScript provides us with three statements for handling errors: try, catch, and finally.

The try statement allows us to define a block of code that may contain errors. The catch statement allows us to define a block of code to run if an error occurs in the try block. The finally statement allows us to define a block of code that will always be executed, whether an error occurs or not.

Here is an example of how to use these statements:

try {
  // Code to try running goes here
} catch (error) {
  // Code to run if an error occurs goes here
} finally {
  // Code to always run goes here
}
HackerRank Challenge

Now let's put our knowledge of try, catch, and finally to the test with the following HackerRank challenge:

Objective

In this challenge, use try, catch, and finally to handle simple errors in a function.

Function

Implement a function named reverseString that reverses a string and throws an error if the input is not a string.

Input Format

  • s - a string variable

Output Format

  • If s is not a string, throw an error.
  • If s is a string, return the reversed string.

Sample Input 0

"1234"

Sample Output 0

"4321"

Sample Input 1

Number(1234)

Sample Output 1

s.split is not a function
1234

Solution

Here is my solution to the HackerRank challenge:

function reverseString(s) {
  try {
    s = s.split("").reverse().join("");
  } catch (error) {
    console.log(error.message);
  } finally {
    console.log(s);
  }
}

In this solution, we define the reverseString function. Inside the function, we use a try statement to attempt to reverse the string by splitting it into an array of characters, reversing the array using the reverse() method, and then joining the reversed array back into a string.

If an error occurs, such as if s is not a string, we catch the error and log the error message to the console using the error.message property.

Finally, we use the finally statement to log the value of s to the console, whether an error occurred or not.

Conclusion

In conclusion, error handling is an important aspect of JavaScript programming, and the try, catch, and finally statements help us to properly handle errors in our code. By using these statements, we can ensure that our code runs smoothly and efficiently.