Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can we re-throw errors in JavaScript? Explain.
Exception can be rethrown after they have been caught by using the throw after catching the exception.
Following is the code to re-throw errors in JavaScript −
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: rebeccapurple;
}
</style>
</head>
<body>
<h1>Re-throw errors in JavaScript</h1>
<input type="number" class="num" />
<button class="Btn">CHECK</button>
<div class="result"></div>
<h3>
Enter a number bigger than 40 to re throw error;
</h3>
<script>
let BtnEle = document.querySelector(".Btn");
let resEle = document.querySelector(".result");
BtnEle.addEventListener("click", () => {
let a = document.querySelector(".num").value;
try {
throw a;
}
catch (err) {
resEle.innerHTML = "Error thrown = " + err + "<br>";
if (a < 40) {
resEle.innerHTML += "Error handled : Value less than 40";
} else {
resEle.innerHTML += "Value more than 40 rethrowing error";
throw err;
}
}
});
</script>
</body>
</html>
Output
The above code will produce the following output −

On entering a value less than 40 and clicking on ‘CHECK’ −

On entering a value bigger than 40 and clicking on ‘CHECK’ −

Advertisements