How does try…catch…finally
work?
In the previous lecture video, you learned how to throw exceptions in your programs. In this lecture video, we will take a look at how to gracefully handle these errors in a try…catch…finally
block.
The try
block is used to wrap code that might throw an error. It acts as a safe space to try something that could fail.
The catch
block captures and handles errors that occur in the try
block. You can use the Error
object inside catch
to inspect what went wrong.
The finally
block runs after the try
and catch
blocks, regardless of whether an error occurred. It’s commonly used for cleanup tasks, such as closing files or releasing resources.
Here is an example of using a try…catch
block:
function processInput(input) {
if (typeof input !== "string") {
throw new TypeError("Input must be a string.");
}
return input.toUpperCase();
}
try {
console.log("Starting to process input...");
const result = processInput(9);
console.log("Processed result:", result);
} catch (error) {
console.error("Error occurred:", error.message);
}
In this example, we have a function called processInput
that first checks if the input
is not of type string
. If that is the case, then we throw an error. Otherwise, we return the result of using the toUpperCase
method on the input
.
We call the function inside of a try
block. Since the function call throws an error, then it will be caught inside the catch
block and the error message will be displayed in the console.
The error passed into the catch
block is an Error
object which contains information about that error. In this case, we are using the message
property which displays human readable information to the user.
We are using the console.error
because it is designed specifically to log errors. In many modern browsers, the output of console.error()
appears in red in the console.
The finally
statement is executed regardless of if an exception was thrown or not.
try {
// Code that might throw an error
} catch (error) {
// Code to handle the error
} finally {
// Code that runs regardless of whether an error occurred or not
}
A good use case for the finally
statement is if you were working with files. In JavaScript, you can open a file, use a try
block to write data to the file. If there are any errors, you can use the catch
to catch those errors. Then use the finally
statement to close the file.